Skip to content

Commit 5e88d33

Browse files
authoredJan 22, 2024
fix: strip locale from path passed to middleware (#194)
1 parent 1dcf088 commit 5e88d33

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed
 

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

+2-1
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 } from './util.ts'
3+
import { normalizeDataUrl, removeBasePath, removeLocaleFromPath } from './util.ts'
44

55
interface I18NConfig {
66
defaultLocale: string
@@ -37,6 +37,7 @@ const normalizeRequestURL = (originalURL: string, nextConfig?: RequestData['next
3737
const url = new URL(originalURL)
3838

3939
url.pathname = removeBasePath(url.pathname, nextConfig?.basePath)
40+
url.pathname = removeLocaleFromPath(url.pathname, nextConfig)
4041

4142
// We want to run middleware for data requests and expose the URL of the
4243
// corresponding pages, so we have to normalize the URLs before running

‎edge-runtime/lib/util.ts

+18-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1-
// If the URL path matches a data URL, we need to normalize it.
2-
// https://github.com/vercel/next.js/blob/25e0988e7c9033cb1503cbe0c62ba5de2e97849c/packages/next/src/shared/lib/router/utils/get-next-pathname-info.ts#L69-L76
1+
import type { RequestData } from './next-request.ts'
2+
3+
/**
4+
* Normalize a data URL into a route path.
5+
* @see https://github.com/vercel/next.js/blob/25e0988e7c9033cb1503cbe0c62ba5de2e97849c/packages/next/src/shared/lib/router/utils/get-next-pathname-info.ts#L69-L76
6+
*/
37
export function normalizeDataUrl(urlPath: string) {
48
if (urlPath.startsWith('/_next/data/') && urlPath.includes('.json')) {
59
const paths = urlPath
@@ -20,6 +24,18 @@ export const removeBasePath = (path: string, basePath?: string) => {
2024
return path
2125
}
2226

27+
export const removeLocaleFromPath = (path: string, nextConfig: RequestData['nextConfig']) => {
28+
if (nextConfig?.i18n) {
29+
for (const locale of nextConfig.i18n.locales) {
30+
const regexp = new RegExp(`^/${locale}($|/)`, 'i')
31+
if (path.match(regexp)) {
32+
return path.replace(regexp, '/') || '/'
33+
}
34+
}
35+
}
36+
return path
37+
}
38+
2339
/**
2440
* This is how Next handles rewritten URLs.
2541
*/

0 commit comments

Comments
 (0)