Skip to content

Commit c32f1f6

Browse files
authored
Fixed language detection for no regional variant #175
This commit refines the approach to extracting language codes from the `Accept-Language` header. By employing a unified regex pattern, the code now efficiently captures both simple language codes and those with regional variants. The language code extraction logic now also splits on both hyphens and underscores, defaulting to the primary language code in cases of regional variants, and always converts the result to lowercase for consistent processing.
1 parent 5a2bfad commit c32f1f6

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

examples/multi-page/src/routes/+layout.server.js

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,21 @@ export const load = async ({ url, cookies, request }) => {
88
let locale = (cookies.get('lang') || '').toLowerCase();
99

1010
// Get user preferred locale
11-
if (!locale) {
12-
locale = `${`${request.headers.get('accept-language')}`.match(/[a-zA-Z]+?(?=-|_|,|;)/)}`.toLowerCase();
13-
}
11+
if (!locale) {
12+
// If no cookie is set, try to determine the locale from the 'Accept-Language' header
13+
const acceptLanguageHeader = request.headers.get('accept-language') || '';
14+
// Attempt to match the language code with optional region code
15+
let match = acceptLanguageHeader.match(/^[a-z]+(?=[-_])/i);
16+
17+
// If no match is found, try to match just the language code
18+
if (!match) {
19+
match = acceptLanguageHeader.match(/^[a-z]+/i);
20+
}
21+
22+
// If a match is found, use it as the locale, otherwise fall back to the default locale
23+
locale = match ? match[0].toLowerCase() : defaultLocale;
24+
}
25+
1426

1527
// Get defined locales
1628
const supportedLocales = locales.get().map((l) => l.toLowerCase());
@@ -26,4 +38,4 @@ export const load = async ({ url, cookies, request }) => {
2638
i18n: { locale, route: pathname },
2739
translations: translations.get(), // `translations` on server contain all translations loaded by different clients
2840
};
29-
};
41+
};

0 commit comments

Comments
 (0)