Skip to content

Commit

Permalink
fix: Correctly handle search params in redirects when using `trailing…
Browse files Browse the repository at this point in the history
…Slash: true` (#1537)

`normalizeTrailingSlash` expects a `pathname` but it's getting pathname
+ search.

This causes redirects to urls like `/users/?sort=asc/`

---------

Co-authored-by: Jan Amann <jan@amann.work>
  • Loading branch information
deini and amannn authored Nov 13, 2024
1 parent 4e3e915 commit 03a4620
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
14 changes: 14 additions & 0 deletions packages/next-intl/src/middleware/middleware.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1125,6 +1125,20 @@ describe('prefix-based routing', () => {
'http://localhost:3000/en/'
);
});

it('keeps search params when redirecting to a locale at the root', () => {
middleware(createMockRequest('/?sort=asc'));
expect(MockedNextResponse.redirect.mock.calls[0][0].toString()).toBe(
'http://localhost:3000/en/?sort=asc'
);
});

it('keeps search params when redirecting to a locale', () => {
middleware(createMockRequest('/users?sort=asc'));
expect(MockedNextResponse.redirect.mock.calls[0][0].toString()).toBe(
'http://localhost:3000/en/users/?sort=asc'
);
});
});

describe('localized pathnames', () => {
Expand Down
4 changes: 3 additions & 1 deletion packages/next-intl/src/middleware/middleware.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,9 @@ export default function createMiddleware<
}

function redirect(url: string, redirectDomain?: string) {
const urlObj = new URL(normalizeTrailingSlash(url), request.url);
const urlObj = new URL(url, request.url);

urlObj.pathname = normalizeTrailingSlash(urlObj.pathname);

if (domainsConfig.length > 0 && !redirectDomain && domain) {
const bestMatchingDomain = getBestMatchingDomain(
Expand Down

0 comments on commit 03a4620

Please sign in to comment.