diff --git a/packages/next-intl/src/middleware/middleware.test.tsx b/packages/next-intl/src/middleware/middleware.test.tsx index 14aa25c5e..7449040eb 100644 --- a/packages/next-intl/src/middleware/middleware.test.tsx +++ b/packages/next-intl/src/middleware/middleware.test.tsx @@ -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', () => { diff --git a/packages/next-intl/src/middleware/middleware.tsx b/packages/next-intl/src/middleware/middleware.tsx index 6ed38e8e2..620bee462 100644 --- a/packages/next-intl/src/middleware/middleware.tsx +++ b/packages/next-intl/src/middleware/middleware.tsx @@ -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(