Enhance getUserLocale to better find the best lang

The current implementation of getUserLocale didn't catch regional
variations of the languages. These are separated by a dash and uppercase
letters. E.g. a user with 'de-CH' didn't get the German translation but
fell back to English.

This new implementation also considers these variations and falls back
to the more general language if the exact variation is not available.

Additionally, instead of navigator.language we now use
navigator.languages, which contains all of the browsers preferred
languages in order. This features is supported by all major browsers
since 2017. ['it', 'de'] will then resolve to German instead of English.
This commit is contained in:
Lenny Angst
2025-07-08 18:22:10 +02:00
parent 9015b07c21
commit 5db4897725
+10 -2
View File
@@ -23,8 +23,16 @@ const resources: Record<string, () => Promise<Record<string, any>>> = {
function getUserLocale(): string {
if (typeof navigator !== 'undefined') {
const lang = navigator.language;
return resources[lang] ? lang : defaultLocale;
for (const lang of navigator.languages) {
if (resources[lang]) {
return lang;
}
// In case of a regional code (e.g. 'de-CH'), fallback to the more general lang
const baseLang = lang.split('-')[0]
if (resources[baseLang]) {
return baseLang
}
}
}
return defaultLocale;
}