@k8ordo/i18n

Switching

Build the links that reopen the current page in another language, and write the choice to a cookie so the next visit to / can use it.

On this page

Destination URL

ts
locales.delocalize('/ja/products/42');
// { locale: 'ja', pathname: '/products/42' }

locales.localize('/products/42', 'en');
// '/en/products/42'

delocalize takes the locale segment off the front of a pathname. localize puts one on.

When the first segment is not a locale, delocalize returns locale: null; english in /english is not one either. It never falls back to the default locale. The caller decides which locale to use.

What is left of /en and of /en/ is /. The other way round, localize('/', 'en') returns /en.

Warning

Pitfall

localize does not check for a segment that is already there: localize('/en/ui', 'ja') is /ja/en/ui, so pass it a pathname that went through delocalize. A value that does not start with / is a TypeError (localize: "products" is not a pathname — it does not start with "/").

Playground

Destination demo

Type a pathname to see what delocalize returns and what localize makes of it for each locale.

delocalize('/ja/products/42')
{ locale: 'ja', pathname: '/products/42' }
localize('/products/42', 'ja')
'/ja/products/42'
localize('/products/42', 'en')
'/en/products/42'

Try it

  1. For the /ja/products/42 already there, locale is ja and pathname is /products/42. The destination for en is /en/products/42.
  2. Change it to /english. The first segment is not a locale, so locale becomes null.
  3. Change it to /en/. The pathname becomes /.
  4. Change it to products, which does not start with /. The demo shows the TypeError message from localize.

Switcher links

src/components/language-switcher.tsx
import type { Variants } from '@k8ordo/i18n';

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

const NAMES: Variants<string> = { ja: '日本語', en: 'English' };

type Props = { pathname: string };

export function LanguageSwitcher({ pathname }: Props) {
  const rest = locales.delocalize(pathname).pathname;
Takes the locale segment off the current pathname
  const current = locales.getLocale();

  return (
    <ul>
      {locales.all.map((locale) => (
        <li key={locale}>
          <a
            aria-current={locale === current ? 'true' : undefined}
            href={locales.localize(rest, locale)}
The destination with each locale’s segment put on
            hrefLang={locale}
            lang={locale}
          >
            {NAMES[locale]}
          </a>
        </li>
      ))}
    </ul>
  );
}

The destinations are built from the current page’s pathname, taken from the app’s router without the base. What usePathname() from @k8ordo/router returns can be passed as it is. See @k8ordo/router’s Location.

A plain <a> is enough. In the render after the move, messages read the new URL’s locale.

Variants<string> holds one value per locale registered in Register. Add a locale and forget its name here, and the type check fails.

Information

Note

localize and delocalize deal in pathnames only, so the query (everything after ?) is not carried over. Append it yourself to keep it.

In an app served under Vite’s base, put the base on the result of localize. See Current locale.

Locale cookie

src/lib/remember-locale.ts
import type { Locale } from '../i18n';

const MAX_AGE = 400 * 24 * 60 * 60 * 1000;

export const rememberLocale = (locale: Locale) =>
  cookieStore.set({
    name: 'locale',
    value: locale,
    sameSite: 'lax',
    expires: Date.now() + MAX_AGE,
  });

On the server, negotiateRequest reads this cookie before Accept-Language.

src/components/language-switcher.tsx
<a
  aria-current={locale === current ? 'true' : undefined}
  href={locales.localize(rest, locale)}
  hrefLang={locale}
  lang={locale}
  onClick={() => {
Written on click, so the switcher becomes a Client Component
    void rememberLocale(locale);
  }}
>

With the Cookie Store API’s defaults, the cookie is gone when the browser closes, and it is written SameSite=Strict, which keeps it off the first request from a link on another site. So the call sets sameSite: 'lax' and an expires 400 days ahead, the longest a browser keeps a cookie.

The app chooses the cookie’s name. Pass the same name to the negotiateRequest that reads it, as { cookie: 'locale' }. The reading side is covered in Negotiation.

Information

Note

A site without a server reads the cookie in the browser, on the / page. That is also shown in Negotiation.

k8ordo

React libraries that use Baseline features without holding back.