@k8ordo/i18n

Negotiation

/ is the one URL without a locale. Here you pick one locale from the languages the visitor asks for and send them to that locale’s URL.

On this page

Choosing from preferred languages

ts
locales.all; // ['ja', 'en', 'en-GB']

locales.negotiate(navigator.languages);

locales.negotiate(['en-GB']); // 'en-GB'
locales.negotiate(['en-US', 'ja']); // 'en'
locales.negotiate(['ja-JP', 'en']); // 'ja'
locales.negotiate(['***', 'en']); // 'en'
locales.negotiate(['fr', 'de']); // 'ja'

locales.negotiate picks one of your defined locales from the visitor’s list of preferred languages. In the browser, navigator.languages can be passed as it is.

  1. Take the requested tags one at a time, from the first.
  2. If that exact tag is defined, return it. Case does not matter: passing en-gb returns en-GB, spelled as it was defined.
  3. Otherwise, return the locale of the same language that was defined first.
  4. If neither exists, move on to the next tag. A tag that is not BCP 47 is skipped without an error.
  5. If nothing matched by the end, return the default locale.

The whole list is never searched for an exact tag first. A visitor who sends ['en-US', 'ja'] wants English most, so if en is defined, the answer is en, even though ja further down is defined exactly.

Information

Note

Languages are compared by Intl.Locale’s language alone, not by script or region. With zh-Hans and zh-Hant defined, passing zh-Hant-TW returns zh-Hans, the one defined first.

Playground

Language selection demo

A demo that picks a locale from an Accept-Language header with this site’s own locales (ja and en, default ja).

Examples
The list parseAcceptLanguage returns
  1. fr-CHno match
  2. frno match
  3. en-USsame language → en
  4. janot looked at (already settled)
What negotiate returns

en

Try it

  1. With the header already there, fr-CH and fr match no locale. en-US matches en by language, so the answer is en.
  2. Press en-US, ja. The answer stays en, and ja is never looked at.
  3. Press en_US, ja;q=0.5. en_US is not BCP 47 and is skipped, so the answer is ja.
  4. Press *;q=0.5, en;q=0, de. * and en, weighted 0, are removed from the list. de matches nothing either, so the answer is the default, ja.
  5. Press “This browser’s navigator.languages” to choose again from this browser’s language settings.

Reading Accept-Language

ts
import { parseAcceptLanguage } from '@k8ordo/i18n';

parseAcceptLanguage('en-US;q=0.8, ja, en;q=0.9');
// ['ja', 'en', 'en-US']

On a server, the request’s Accept-Language header is what the visitor asks for. parseAcceptLanguage turns it into an array negotiate accepts.

  • Tags are ordered by their q weight, highest first. A tag without one weighs 1.
  • Tags of equal weight keep the header’s order.
  • Tags weighted 0 or less, and *, are removed. When nothing matches, the default locale is used anyway, so * adds nothing.
  • A q that is not a number is ignored, and the tag keeps a weight of 1.
  • A missing header (null) or a blank one gives an empty array.

The tags themselves are not checked. negotiate skips the ones that are not BCP 47.

Choosing from a request

ts
locales.negotiateRequest(request, { cookie: 'locale' });

negotiateRequest picks a locale from a Request. Give it a cookie name in cookie, and the language the visitor chose before is read from that cookie first, then Accept-Language.

The cookie’s value and the header’s list go through the same negotiate rules. A cookie still holding a locale that is no longer defined falls through to the header. Without cookie, only the header is read.

Writing the cookie is covered in Switching, under “Locale cookie”.

/ on a server

src/lib/redirect-to-locale.ts
import { locales } from '../i18n';

export function redirectToLocale(request: Request): Response {
  const locale = locales.negotiateRequest(request, {
The cookie first, then Accept-Language
    cookie: 'locale',
  });
  return new Response(null, {
    status: 307,
307, since the answer depends on who asks
    headers: { location: locales.localize('/', locale) },
  });
}

When a server answers requests for /, it can redirect without rendering a page. Pick a locale with negotiateRequest and return a 307 to that locale’s URL.

localize leaves out Vite’s base. In an app served under one, add it before using the pathname as the destination.

In @k8ordo/framework, this goes in a guard.ts that answers / alone under server mode, and the next section’s code goes in the / page under static mode. See @k8ordo/framework’s Routing.

/ in the browser

src/components/root-redirect.tsx
'use client';

import { useEffect } from 'react';

import { locales } from '../i18n';

export function RootRedirect() {
  useEffect(() => {
    const locale = locales.negotiate(navigator.languages);
    location.replace(locales.localize('/', locale));
  }, []);

  return null;
}

A site without a server picks the locale in the browser, on the / page. The page renders nothing and moves to the URL of the locale negotiate picks.

  • The move happens in a useEffect. A render on a server or at build time has neither location nor the visitor’s navigator.languages.
  • location.replace replaces the history entry, so the back button never returns to / only to be sent on again.
Information

Note

A visitor without JavaScript stays on /.

src/components/root-redirect.tsx
useEffect(() => {
  void cookieStore.get('locale').then((saved) => {
    const locale = locales.negotiate([
      ...(saved?.value === undefined ? [] : [saved.value]),
      ...navigator.languages,
    ]);
    location.replace(locales.localize('/', locale));
  });
}, []);

If the chosen language is kept in a cookie, put its value in front of navigator.languages and hand both to negotiate. That is the order negotiateRequest reads them in on a server.

k8ordo

React libraries that use Baseline features without holding back.