Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle middleware redirects to default locale and same path #2636

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 9 additions & 12 deletions edge-runtime/lib/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ interface BuildResponseOptions {
request: Request
result: FetchEventResult
nextConfig?: RequestData['nextConfig']
requestLocale?: string
}

export const buildResponse = async ({
Expand All @@ -33,7 +32,6 @@ export const buildResponse = async ({
request,
result,
nextConfig,
requestLocale,
}: BuildResponseOptions): Promise<Response | void> => {
logger
.withFields({ is_nextresponse_next: result.response.headers.has('x-middleware-next') })
Expand Down Expand Up @@ -197,11 +195,10 @@ export const buildResponse = async ({
return addMiddlewareHeaders(context.rewrite(target), res)
}

// If we are redirecting a request that had a locale in the URL, we need to add it back in
if (redirect && requestLocale) {
redirect = normalizeLocalizedTarget({ target: redirect, request, nextConfig, requestLocale })
if (redirect) {
redirect = normalizeLocalizedTarget({ target: redirect, request, nextConfig })
if (redirect === request.url) {
logger.withFields({ rewrite_url: rewrite }).debug('Rewrite url is same as original url')
logger.withFields({ redirect_url: redirect }).debug('Redirect url is same as original url')
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this seems like was previously c&p-ed from rewrite handling so log fields/msg was off

return
}
res.headers.set('location', redirect)
Expand Down Expand Up @@ -234,25 +231,25 @@ function normalizeLocalizedTarget({
target,
request,
nextConfig,
requestLocale,
}: {
target: string
request: Request
nextConfig?: RequestData['nextConfig']
requestLocale?: string
}) {
}): string {
const targetUrl = new URL(target, request.url)

const normalizedTarget = normalizeLocalePath(targetUrl.pathname, nextConfig?.i18n?.locales)

const locale = normalizedTarget.detectedLocale ?? requestLocale
if (
locale &&
normalizedTarget.detectedLocale &&
!normalizedTarget.pathname.startsWith(`/api/`) &&
!normalizedTarget.pathname.startsWith(`/_next/static/`)
) {
targetUrl.pathname =
addBasePath(`/${locale}${normalizedTarget.pathname}`, nextConfig?.basePath) || `/`
addBasePath(
`/${normalizedTarget.detectedLocale}${normalizedTarget.pathname}`,
nextConfig?.basePath,
) || `/`
} else {
targetUrl.pathname = addBasePath(normalizedTarget.pathname, nextConfig?.basePath) || `/`
}
Expand Down
1 change: 0 additions & 1 deletion edge-runtime/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ export async function handleMiddleware(
logger: reqLogger,
request,
result,
requestLocale: nextRequest.detectedLocale,
nextConfig,
})

Expand Down
5 changes: 5 additions & 0 deletions tests/fixtures/middleware-i18n/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ export async function middleware(request) {
return Response.redirect(new URL('/new-home#fragment', url))
}

if (url.locale !== 'en' && url.pathname === '/redirect-to-same-page-but-default-locale') {
url.locale = 'en'
return Response.redirect(url)
}

if (url.pathname.includes('/json')) {
return NextResponse.json({
requestUrlPathname: new URL(request.url).pathname,
Expand Down
24 changes: 24 additions & 0 deletions tests/integration/edge-handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,30 @@ describe('page router', () => {
expect(response.status).toBe(302)
})

test<FixtureTestContext>('should support redirects to default locale without changing path', async (ctx) => {
await createFixture('middleware-i18n', ctx)
await runPlugin(ctx)
const origin = await LocalServer.run(async (req, res) => {
res.write(
JSON.stringify({
url: req.url,
headers: req.headers,
}),
)
res.end()
})
ctx.cleanup?.push(() => origin.stop())
const response = await invokeEdgeFunction(ctx, {
functions: ['___netlify-edge-handler-middleware'],
origin,
url: `/fr/redirect-to-same-page-but-default-locale`,
redirect: 'manual',
})
const url = new URL(response.headers.get('location') ?? '', 'http://n/')
expect(url.pathname).toBe('/redirect-to-same-page-but-default-locale')
expect(response.status).toBe(302)
})

test<FixtureTestContext>('should preserve locale in request.nextUrl', async (ctx) => {
await createFixture('middleware-i18n', ctx)
await runPlugin(ctx)
Expand Down
Loading