Skip to content

Commit 59b575e

Browse files
authoredMay 27, 2024
fix: ensure locale is in next response url to allow page locale to inferred downstream (#533)
* fix: ensure locale is in next request to allow page locale to be calculated downstream * test: Add checks for nextRequest locale
1 parent ca0c368 commit 59b575e

File tree

5 files changed

+39
-7
lines changed

5 files changed

+39
-7
lines changed
 

‎edge-runtime/lib/next-request.ts

+7-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { Context } from '@netlify/edge-functions'
22

3-
import { normalizeDataUrl, removeBasePath, normalizeLocalePath, addBasePath } from './util.ts'
3+
import { addBasePath, normalizeDataUrl, normalizeLocalePath, removeBasePath } from './util.ts'
44

55
interface I18NConfig {
66
defaultLocale: string
@@ -74,6 +74,11 @@ const normalizeRequestURL = (
7474
url.pathname = addBasePath(url.pathname, nextConfig?.basePath)
7575
}
7676

77+
// keep the locale in the url for request.nextUrl object
78+
if (detectedLocale) {
79+
url.pathname = `/${detectedLocale}${url.pathname}`
80+
}
81+
7782
return {
7883
url: url.toString(),
7984
detectedLocale,
@@ -88,9 +93,9 @@ export const buildNextRequest = (
8893
const { url, method, body, headers } = request
8994
const { country, subdivision, city, latitude, longitude, timezone } = context.geo
9095
const geo: RequestData['geo'] = {
96+
city,
9197
country: country?.code,
9298
region: subdivision?.code,
93-
city,
9499
latitude: latitude?.toString(),
95100
longitude: longitude?.toString(),
96101
timezone,

‎edge-runtime/lib/util.ts

-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import type { RequestData } from './next-request.ts'
2-
31
/**
42
* Normalize a data URL into a route path.
53
* @see https://github.com/vercel/next.js/blob/25e0988e7c9033cb1503cbe0c62ba5de2e97849c/packages/next/src/shared/lib/router/utils/get-next-pathname-info.ts#L69-L76

‎edge-runtime/middleware.ts

+2-3
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,11 @@ import nextConfig from './next.config.json' assert { type: 'json' }
66
import { InternalHeaders } from './lib/headers.ts'
77
import { logger, LogLevel } from './lib/logging.ts'
88
import { buildNextRequest, RequestData } from './lib/next-request.ts'
9-
import { buildResponse } from './lib/response.ts'
10-
import { FetchEventResult } from './lib/response.ts'
9+
import { buildResponse, FetchEventResult } from './lib/response.ts'
1110
import {
12-
type MiddlewareRouteMatch,
1311
getMiddlewareRouteMatcher,
1412
searchParamsToUrlQuery,
13+
type MiddlewareRouteMatch,
1514
} from './lib/routing.ts'
1615

1716
type NextHandler = (params: { request: RequestData }) => Promise<FetchEventResult>

‎tests/fixtures/middleware-i18n/middleware.js

+4
Original file line numberDiff line numberDiff line change
@@ -80,4 +80,8 @@ export async function middleware(request) {
8080
console.log(String(new URL('/new-home#fragment', url)))
8181
return Response.redirect(new URL('/new-home#fragment', url))
8282
}
83+
84+
if (url.pathname.includes('/json')) {
85+
return NextResponse.json({ url: request.nextUrl.href, locale: request.nextUrl.locale })
86+
}
8387
}

‎tests/integration/edge-handler.test.ts

+26
Original file line numberDiff line numberDiff line change
@@ -499,4 +499,30 @@ describe('page router', () => {
499499
expect(url.pathname).toBe('/fr/new-home')
500500
expect(response.status).toBe(302)
501501
})
502+
503+
test<FixtureTestContext>('should preserve locale in request.nextUrl', async (ctx) => {
504+
await createFixture('middleware-i18n', ctx)
505+
await runPlugin(ctx)
506+
const origin = await LocalServer.run(async (req, res) => {
507+
res.write(
508+
JSON.stringify({
509+
url: req.url,
510+
headers: req.headers,
511+
}),
512+
)
513+
res.end()
514+
})
515+
ctx.cleanup?.push(() => origin.stop())
516+
const response = await invokeEdgeFunction(ctx, {
517+
functions: ['___netlify-edge-handler-middleware'],
518+
origin,
519+
url: `/fr/json`,
520+
})
521+
expect(response.status).toBe(200)
522+
523+
const body = await response.json()
524+
const bodyUrl = new URL(body.url)
525+
expect(bodyUrl.pathname).toBe('/fr/json')
526+
expect(body.locale).toBe('fr')
527+
})
502528
})

0 commit comments

Comments
 (0)