Skip to content

Commit 1cb0463

Browse files
authored
🐛 Fix lang detection (#1281)
Co-authored-by: Benjamin Arias <12382534+bjlaa@users.noreply.github.com>
1 parent 2367d3a commit 1cb0463

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/i18nConfig.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { Config } from 'next-i18n-router/dist/types'
2+
import type { NextRequest } from 'next/server'
23

34
export const LOCALE_EN_KEY = 'en'
45
export const LOCALE_ES_KEY = 'es'
@@ -17,6 +18,25 @@ const i18nConfig: Config = {
1718
maxAge: 31536000,
1819
secure: true, // Required when using SameSite=None
1920
},
21+
localeDetector: (request: NextRequest, config: Config): string => {
22+
// Check for NEXT_LOCALE cookie
23+
const nextLocale = request.cookies.get(NEXT_LOCALE_COOKIE_NAME)?.value
24+
if (nextLocale && config.locales.includes(nextLocale)) {
25+
return nextLocale
26+
}
27+
28+
// Check browser language
29+
const acceptLanguage = request.headers.get('accept-language')
30+
if (acceptLanguage) {
31+
const browserLang = acceptLanguage.split(',')[0].split('-')[0]
32+
if (config.locales.includes(browserLang)) {
33+
return browserLang
34+
}
35+
}
36+
37+
// Return default locale
38+
return config.defaultLocale
39+
},
2040
}
2141

2242
export default i18nConfig

0 commit comments

Comments
 (0)