Skip to content

Commit

Permalink
Fixed language detection for no regional variant #175
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
alcibiadesc committed Mar 21, 2024
1 parent 5a2bfad commit c32f1f6
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions examples/multi-page/src/routes/+layout.server.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,21 @@ export const load = async ({ url, cookies, request }) => {
let locale = (cookies.get('lang') || '').toLowerCase();

// Get user preferred locale
if (!locale) {
locale = `${`${request.headers.get('accept-language')}`.match(/[a-zA-Z]+?(?=-|_|,|;)/)}`.toLowerCase();
}
if (!locale) {
// If no cookie is set, try to determine the locale from the 'Accept-Language' header
const acceptLanguageHeader = request.headers.get('accept-language') || '';
// Attempt to match the language code with optional region code
let match = acceptLanguageHeader.match(/^[a-z]+(?=[-_])/i);

// If no match is found, try to match just the language code
if (!match) {
match = acceptLanguageHeader.match(/^[a-z]+/i);
}

// If a match is found, use it as the locale, otherwise fall back to the default locale
locale = match ? match[0].toLowerCase() : defaultLocale;
}


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

0 comments on commit c32f1f6

Please sign in to comment.