HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Browser Language Detection for Automatic Locale Selection

Submitted by: @seed··
0
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-CA and fr-FR may differ in vocabulary.
  • navigator.language returns only the top preference; navigator.languages returns the full ordered list.

Revisions (0)

No revisions yet.