Skip to content

Commit 9be3382

Browse files
authored
fix: custom headers for root route when using i18n (#1893)
* fix: escape locale strings when matching from routes-manifest * chore: amend i18n headers test to cover regex special characters
1 parent 909cf70 commit 9be3382

File tree

3 files changed

+12
-4
lines changed

3 files changed

+12
-4
lines changed

packages/runtime/src/helpers/config.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import slash from 'slash'
99
import { HANDLER_FUNCTION_NAME, ODB_FUNCTION_NAME } from '../constants'
1010

1111
import type { RoutesManifest } from './types'
12+
import { escapeStringRegexp } from './utils'
1213

1314
const ROUTES_MANIFEST_FILE = 'routes-manifest.json'
1415

@@ -214,7 +215,9 @@ export const generateCustomHeaders = (nextConfig: NextConfig, netlifyHeaders: Ne
214215

215216
if (useLocale) {
216217
const { locales } = i18n
217-
const joinedLocales = locales.join('|')
218+
219+
// escape the locale strings to match the way Next writes the routes-manifest.json file
220+
const joinedLocales = locales.map((locale: string) => escapeStringRegexp(locale)).join('|')
218221

219222
/**
220223
* converts e.g.

packages/runtime/src/helpers/utils.ts

+5
Original file line numberDiff line numberDiff line change
@@ -313,3 +313,8 @@ export const getRemotePatterns = (experimental: ExperimentalConfigWithLegacy, im
313313
}
314314
return []
315315
}
316+
317+
// Taken from next/src/shared/lib/escape-regexp.ts
318+
const reHasRegExp = /[|\\{}()[\]^$+*?.-]/
319+
const reReplaceRegExp = /[|\\{}()[\]^$+*?.-]/g
320+
export const escapeStringRegexp = (str: string) => (reHasRegExp.test(str) ? str.replace(reReplaceRegExp, '\\$&') : str)

test/index.spec.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -1606,13 +1606,13 @@ describe('function helpers', () => {
16061606
// Next.js has modified the routesManifest to have the locales in the source.
16071607
const nextConfig = {
16081608
i18n: {
1609-
locales: ['en', 'fr'],
1609+
locales: ['en-US', 'fr'],
16101610
defaultLocale: 'en',
16111611
},
16121612
routesManifest: {
16131613
headers: [
16141614
{
1615-
source: '/:nextInternalLocale(en|fr)/with-locale/:path*',
1615+
source: '/:nextInternalLocale(en\\-US|fr)/with-locale/:path*',
16161616
headers: [
16171617
{
16181618
key: 'X-Unit-Test',
@@ -1635,7 +1635,7 @@ describe('function helpers', () => {
16351635
},
16361636
},
16371637
{
1638-
for: '/en/with-locale/*',
1638+
for: '/en-US/with-locale/*',
16391639
values: {
16401640
'X-Unit-Test': 'true',
16411641
},

0 commit comments

Comments
 (0)