Skip to content

Commit eb20538

Browse files
Merge pull request #176 from alcibiadesc/patch-2
Fixed language detection for no regional variant #175
2 parents 666439b + c32f1f6 commit eb20538

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

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

+16-4
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)