@k8ordo/i18n

Current locale

In the browser the first segment of the URL is the current locale; on the server it is the one locales.run or paramsSchema set. You will be able to read its tag with getLocale() and write it into <html lang>.

On this page

Locale in the browser

In the browser, the first segment of location.pathname is the locale. Messages read the URL each time they are called. When the first segment is not a locale of the set, the default locale is used.

With no state to hold a locale, locales.run has no use in the browser. Calling it there fails with locales.run: in the browser the URL is the locale — navigate instead.

To change the locale, navigate to the same pathname under another locale’s segment. The page renders again, and its messages read the new URL’s locale. How to write it is covered in Switching.

Locale on the server

src/lib/welcome.ts
import { locales } from '../i18n';
import type { Locale } from '../i18n';
import { welcomeSubject } from '../messages/email';

export const subjectIn = (locale: Locale) =>
  locales.run(locale, () => welcomeSubject());

On the server, a message reads the locale set for the current async context. To call messages for an email subject or a batch job, wrap the call in locales.run(locale, fn). fn, and everything it starts, runs in that locale, and the locale is kept across awaits when fn is async. run returns what fn returns.

locales.paramsSchema is a Standard Schema that validates { locale }. When it accepts a locale, it sets that locale for the rest of the async context that called it. In @k8ordo/framework, exporting it from the [locale] layout sets the locale for the page’s render and for the Server Actions posted from that page. See @k8ordo/framework’s Routing.

When neither has set a locale, the default locale is used; a message never reads the request’s URL or headers. When a page renders on the server, set the locale named by the first segment of the request’s URL. Otherwise the text a Client Component writes on the server disagrees with what the browser renders when it hydrates.

Warning

Pitfall

On a runtime without AsyncLocalStorage, run and paramsSchema throw, with a message that starts with the caller’s name, such as locales.run: this runtime has no AsyncLocalStorage to scope a locale to. Neither goes on in the default locale.

The locale tag

src/components/region-name.tsx
import { locales } from '../i18n';

export function RegionName({ code }: { code: string }) {
  const names = new Intl.DisplayNames(locales.getLocale(), {
    type: 'region',
  });
  return <>{names.of(code)}</>;
}

When you need the locale tag itself, call locales.getLocale(). In the browser it returns the first segment of the URL; on the server, the locale run or paramsSchema set. It is not a hook, so it can be called anywhere.

getLocale can be destructured and exported: export const { getLocale } = locales.

Information

Note

getLocale() does not subscribe to the URL. In a Client Component it reads the URL at the moment it is called. A component that must re-render when the URL changes uses usePathname() from @k8ordo/router. See @k8ordo/router’s Location.

<html lang> and dir

src/components/document.tsx
import type { ReactNode } from 'react';

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

export function Document({ children }: { children: ReactNode }) {
  const locale = locales.getLocale();

  return (
    <html dir={locales.definitions[locale].dir} lang={locale}>
      <body>{children}</body>
    </html>
  );
}

lang and dir have to be right in the HTML the server writes, because crawlers and screen readers read it without waiting for hydration.

In a render where no locale is set, read it from the pathname instead: locales.delocalize(pathname).locale ?? locales.default. delocalize returns null when the first segment is not a locale, so the caller supplies the default.

Vite’s base

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

// base: '/docs/', URL: '/docs/en/ui'
locales.delocalize('/en/ui');
// { locale: 'en', pathname: '/ui' }
locales.localize('/ui', 'ja');
// '/ja/ui'

When the app is served under a path such as /docs/, the locale is still the first segment below the base. /docs/en/ui is in en.

localize and delocalize take and return pathnames without the base. Put the base back before navigating.

usePathname() from @k8ordo/router returns the pathname without the base, and its withBase adds the base back. See @k8ordo/router’s Base path.

k8ordo

React libraries that use Baseline features without holding back.