patternjavascriptModerate
Browser Language Detection for Automatic Locale Selection
Viewed 0 times
language detectionAccept-Languagenavigator.languagelocale negotiationauto localebrowser language
Problem
Users arrive at a site in the wrong language because the app does not detect their browser's preferred language.
Solution
On the server, read the
Accept-Language header and negotiate the best-matching locale. On the client, use navigator.languages.import { match } from '@formatjs/intl-localematcher';
import Negotiator from 'negotiator';
function getLocale(request) {
const headers = { 'accept-language': request.headers.get('accept-language') ?? '' };
const languages = new Negotiator({ headers }).languages();
const locales = ['en', 'fr', 'de', 'ar'];
try {
return match(languages, locales, 'en');
} catch {
return 'en';
}
}
// Client-side fallback
const preferredLocale = navigator.languages
.find(lang => supportedLocales.includes(lang.split('-')[0]))
?? 'en';Why
Accept-Language is the standard HTTP mechanism for locale negotiation. It contains an ordered list with quality values, making it more reliable than IP geolocation for language preference.Gotchas
- Always allow users to manually override the detected locale and persist their choice in a cookie.
- Never redirect users from their manually selected locale based on language detection — that creates a frustrating loop.
- Region subtags matter:
fr-CAandfr-FRmay differ in vocabulary. navigator.languagereturns only the top preference;navigator.languagesreturns the full ordered list.
Revisions (0)
No revisions yet.