# Internationalisation

> A site in several languages - a URL per locale, stored pages for each, translations, hreflang links and a language switcher.

Put the locale in the URL. Every page lives under a `[locale]` folder, so
`/en/about` and `/fr/about` are two URLs, each stored at build time with its
own `<html lang>`:

```text
src/
  i18n.ts                the locales, and negotiate()
  messages/
    en.json
    fr.json
  app/
    layout.tsx           metadataBase, and no <html>
    route.ts             /  → /en or /fr, by Accept-Language
    not-found.tsx
    sitemap.ts
    [locale]/
      layout.tsx         <html lang={locale}>, and the list of locales
      page.tsx           /en, /fr
      about/
        page.tsx         /en/about, /fr/about
```

This works the same with no backend, a Laravel backend and a Go backend.
Translating your backend's data is [the last step](#translating-backend-data).

## Declaring the locales

Keep the list in one module, beside the check for it:

```ts title="src/i18n.ts"
export const locales = ['en', 'fr'] as const;
export type Locale = (typeof locales)[number];
export const defaultLocale: Locale = 'en';

export function isLocale(value: string | undefined): value is Locale {
  return (locales as readonly (string | undefined)[]).includes(value);
}
```

## The locale layout

`app/[locale]/layout.tsx` is the layout that writes `<html>`, so it can set
`lang`. It lists the locales once, and refuses any other:

```tsx title="src/app/[locale]/layout.tsx"
import type { ReactNode } from 'react';
import { notFound } from '@rsc-kit/core/not-found';
import { isLocale, locales } from '../../i18n';

export function generateStaticParams() {
  return locales.map((locale) => ({ locale }));
}

export default async function LocaleLayout({
  children,
  params,
}: {
  children: ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;

  if (!isLocale(locale)) notFound();

  return (
    <html lang={locale}>
      <body>{children}</body>
    </html>
  );
}
```

- **Every page beneath it is stored once per locale.** A layout's
  `generateStaticParams` lists the values of its own folder for every page
  under it, so `about/page.tsx` lists nothing and is built as `/en/about` and
  `/fr/about`.
- **A locale you don't support is a 404.** `/de/about` isn't stored, so it's
  rendered on request, and `notFound()` answers it.
- **A page with a param of its own** lists only that param, and gets the
  locale it's being built for:

  ```tsx title="src/app/[locale]/blog/[slug]/page.tsx"
  export async function generateStaticParams({ params }: { params: { locale: string } }) {
    return (await postsIn(params.locale)).map((post) => ({ slug: post.slug }));
  }
  ```

The layout at `app/layout.tsx` stays, without `<html>`. It holds what is the
same in every language, such as `metadataBase`, which the sitemap and the
`hreflang` links need to make their URLs absolute:

```tsx title="src/app/layout.tsx"
import type { ReactNode } from 'react';
import type { Metadata } from '@rsc-kit/core/metadata';

export const metadata: Metadata = { metadataBase: new URL('https://example.com') };

export default function RootLayout({ children }: { children: ReactNode }) {
  return children;
}
```

A `not-found.tsx` beside it answers URLs no route owns, `/de/about` included,
and renders inside this layout only, so it writes its own `<html>`:

```tsx title="src/app/not-found.tsx"
export default function NotFound() {
  return (
    <html lang="en">
      <body>
        <h1>Page not found</h1>
      </body>
    </html>
  );
}
```

## Sending `/` to a language

`/` picks a locale and redirects. A `route.ts` does it, because it's the one
URL that has to read the request:

```ts title="src/app/route.ts"
import { isLocale, negotiate } from '../i18n';

export function GET(request: Request): Response {
  const saved = /(?:^|;\s*)locale=([^;]+)/.exec(request.headers.get('cookie') ?? '')?.[1];
  const locale = isLocale(saved) ? saved : negotiate(request.headers.get('accept-language'));

  return new Response(null, {
    status: 307,
    headers: { Location: `/${locale}`, Vary: 'Accept-Language, Cookie' },
  });
}
```

A choice the visitor made with the [language switcher](#switching-language)
wins; otherwise their browser's languages are matched against yours:

```ts title="src/i18n.ts"
/** The best supported match for an Accept-Language header, or the default. */
export function negotiate(header: string | null): Locale {
  const wanted = (header ?? '')
    .split(',')
    .map((part) => {
      const [tag, ...params] = part.trim().toLowerCase().split(';');
      const q = params.find((p) => p.trim().startsWith('q='));

      return { tag: tag.trim(), q: q ? Number(q.trim().slice(2)) : 1 };
    })
    .filter((entry) => entry.tag && entry.q > 0)
    .sort((a, b) => b.q - a.q);

  for (const { tag } of wanted) {
    if (isLocale(tag)) return tag;
    if (isLocale(tag.split('-')[0])) return tag.split('-')[0] as Locale;
  }

  return defaultLocale;
}
```

`fr-CA,fr;q=0.9,en;q=0.8` goes to `/fr`, `de-DE,de;q=0.9` to `/en`.

Keep the request out of the `[locale]` pages. A page that reads `headers()` or
`cookies()` is rendered for every visitor instead of stored, and one that reads
them above every `<Suspense>` boundary is refused by the build. Only `/` needs
to know who is asking.

## Translating

Keep each language's strings in a JSON file, and load the one a page needs in
a server component:

```json title="src/messages/fr.json"
{
  "home": { "title": "Bienvenue", "intro": "Bonjour !" },
  "nav": { "about": "À propos" },
  "counter": { "label": "Clics" }
}
```

```ts title="src/messages.ts"
import type { Locale } from './i18n';

const catalogs = {
  en: () => import('./messages/en.json'),
  fr: () => import('./messages/fr.json'),
};

export type Messages = typeof import('./messages/en.json');

export async function messages(locale: Locale): Promise<Messages> {
  return (await catalogs[locale]()).default;
}
```

```tsx title="src/app/[locale]/page.tsx"
import { messages } from '../../messages';
import { Counter } from '../../components/Counter';
import type { Locale } from '../../i18n';

const launch = Date.UTC(2026, 0, 15);

export default async function Home({ params }: { params: Promise<{ locale: Locale }> }) {
  const { locale } = await params;
  const t = await messages(locale);

  return (
    <main>
      <h1>{t.home.title}</h1>
      <p>{t.home.intro}</p>
      <p>{new Intl.DateTimeFormat(locale, { dateStyle: 'long', timeZone: 'UTC' }).format(launch)}</p>
      <p>{new Intl.NumberFormat(locale, { style: 'currency', currency: 'EUR' }).format(1234.5)}</p>
      <Counter label={t.counter.label} />
    </main>
  );
}
```

- **The catalogues never reach the browser.** They're imported by server
  components, so a page ships none of them.
- **A client component gets its words as props**, as `Counter` gets `label`.
  Pass the strings it shows, not the whole catalogue.
- **`Intl` formats dates, numbers and currencies** in the page's locale, with
  nothing to install: `15 janvier 2026` and `1 234,50 €` on `/fr`,
  `January 15, 2026` and `€1,234.50` on `/en`. A stored page is formatted at
  build, so name the `timeZone` rather than taking the build machine's.

## Links

A link stays in the current locale. Build its href with a helper whose return
type is still a route, so a typo fails the typecheck:

```ts title="src/i18n.ts"
export function localized<P extends string>(locale: Locale, path: P): `/${Locale}${P}` {
  return `/${locale}${path}`;
}
```

```tsx
<Link href={localized(locale, '/about')}>{t.nav.about}</Link>
```

## Switching language

A switcher links to the same page in another locale, and remembers the choice
so `/` sends the visitor there next time. A server action sets the cookie and
redirects:

```ts title="src/actions.ts"
'use server';

import { cookies } from '@rsc-kit/core/request';
import { redirect } from '@rsc-kit/core/redirect';
import { isLocale, locales } from './i18n';

export async function chooseLocale(form: FormData): Promise<void> {
  const locale = String(form.get('locale'));

  if (!isLocale(locale)) return;

  (await cookies()).set('locale', locale, { path: '/', maxAge: 60 * 60 * 24 * 365, sameSite: 'lax' });

  // The path without its locale: /fr/about → /about.
  const rest = String(form.get('path')).replace(new RegExp(`^/(${locales.join('|')})(?=/|$)`), '');

  redirect(`/${locale}${rest.startsWith('/') ? rest : ''}` as never);
}
```

```tsx title="src/components/LanguageSwitcher.tsx"
'use client';

import { usePathname } from '@rsc-kit/core/usePathname';
import { chooseLocale } from '../actions';
import type { Locale } from '../i18n';

export function LanguageSwitcher({ names }: { names: Record<Locale, string> }) {
  const path = usePathname();

  return (
    <form action={chooseLocale}>
      <input type="hidden" name="path" value={path} />
      {Object.entries(names).map(([locale, name]) => (
        <button key={locale} name="locale" value={locale}>{name}</button>
      ))}
    </form>
  );
}
```

```tsx
<LanguageSwitcher names={{ en: 'English', fr: 'Français' }} />
```

## Telling search engines

Each page names its translations with `alternates`. They render as
`<link rel="alternate" hreflang>` and `<link rel="canonical">`, made absolute
with `metadataBase`:

```tsx title="src/app/[locale]/about/page.tsx"
import type { GenerateMetadata } from '@rsc-kit/core/metadata';
import { locales, type Locale } from '../../../i18n';
import { messages } from '../../../messages';

export const generateMetadata: GenerateMetadata<{ locale: Locale }> = async ({ params }) => {
  const { locale } = await params;

  return {
    title: (await messages(locale)).about.title,
    alternates: {
      canonical: `/${locale}/about`,
      languages: {
        ...Object.fromEntries(locales.map((l) => [l, `/${l}/about`])),
        'x-default': '/en/about',
      },
    },
  };
};
```

```html
<link rel="canonical" href="https://example.com/fr/about">
<link rel="alternate" hreflang="en" href="https://example.com/en/about">
<link rel="alternate" hreflang="fr" href="https://example.com/fr/about">
<link rel="alternate" hreflang="x-default" href="https://example.com/en/about">
```

`x-default` is the page for a visitor whose language is none of yours. Put the
locale in `openGraph.locale` too, if the page sets a share card.

The sitemap takes the same map per URL, as `xhtml:link` entries:

```ts title="src/app/sitemap.ts"
import type { MetadataRoute } from '@rsc-kit/core/metadata';
import { locales } from '../i18n';

export default function sitemap(): MetadataRoute.Sitemap {
  return ['', '/about'].flatMap((path) =>
    locales.map((locale) => ({
      url: `/${locale}${path}`,
      alternates: { languages: Object.fromEntries(locales.map((l) => [l, `/${l}${path}`])) },
    })),
  );
}
```

## Translating backend data

When the data comes from a backend through `rpc()`, pass the locale as an
argument:

```tsx title="src/app/[locale]/blog/[slug]/page.tsx"
async function PostBody({ locale, slug }: { locale: Locale; slug: string }) {
  const post = await rpc<Post>('Posts.show', locale, slug);

  return <article><h1>{post.title}</h1><p>{post.published}</p></article>;
}
```

The backend does not see the visitor's `Accept-Language`, and shouldn't need
to:

- **A stored page's calls are made at build, as nobody.** There's no browser
  to have a language, only the argument.
- **A call forwards `Cookie` and `Authorization`, not `Accept-Language`.** And
  a page is stored per URL, so its data has to follow the URL, not the
  visitor's browser.
- **The argument is part of what is stored.** `rpc('Posts.show', 'fr', slug)`
  is answered once at build for `/fr/blog/{slug}` and once for the English
  one, the same on every backend.

### Laravel

On Laravel the page lives under `resources/js/app/[locale]`. Take the locale
as the first parameter, check it, and translate with Laravel's own helpers:

```php title="app/Rsc/Posts.php"
namespace App\Rsc;

use App\Models\Post;
use Illuminate\Support\Facades\App;

class Posts
{
    public function show(string $locale, string $slug): array
    {
        abort_unless(in_array($locale, ['en', 'fr'], true), 404);

        App::setLocale($locale);

        $post = Post::where('slug', $slug)->firstOrFail();

        return [
            'title' => $post->title,
            'published' => $post->published_at->translatedFormat('j F Y'),
            'comments' => trans_choice('posts.comments', $post->comments_count),
        ];
    }
}
```

`__()`, `trans_choice()` and Carbon's `translatedFormat()` all follow
`App::setLocale()`. Set it in every function that translates: the calls a page
makes in one render reach Laravel as one batch, so a function that doesn't set
it gets whichever locale the call before it set.

The `locale` cookie the switcher sets is read by the renderer, not Laravel. If
Laravel should read it too, for a mail it sends in the visitor's language say,
exclude it from encryption, since the renderer wrote it in plain text:

```php title="bootstrap/app.php"
->withMiddleware(function (Middleware $middleware) {
    $middleware->encryptCookies(except: ['locale']);
})
```

### Go

Take the locale as the first parameter, check it, and pick the catalogue for
it. [`golang.org/x/text/message`](https://pkg.go.dev/golang.org/x/text/message)
holds the strings and formats numbers for a language:

```go title="posts.go"
func init() {
    message.SetString(language.French, "%d comments", "%d commentaires")
}

var supported = map[string]language.Tag{"en": language.English, "fr": language.French}

reg.Handle("Posts.show", func(ctx context.Context, locale, slug string) (Post, error) {
    tag, ok := supported[locale]
    if !ok {
        return Post{}, rsckit.Refuse(404, "no such language")
    }

    post, err := db.Post(ctx, slug, locale)
    if err != nil {
        return Post{}, err
    }

    post.Comments = message.NewPrinter(tag).Sprintf("%d comments", post.CommentCount)

    return post, nil
})
```

## How it is stored

- **A layout's `generateStaticParams` is asked first, then each one below it**,
  once per value the ones above chose, as Next does. The URLs built are every
  combination, each once.
- **A route counts as listed** when its page lists its params, or layouts above
  it list every param it has between them. A route that is listed and asked
  for a value it didn't list is rendered on request, which is why `/de` reaches
  the layout's `notFound()` rather than a stored page.
- **The layout that writes `<html>` can be any layout,** not only
  `app/layout.tsx`. One there that returns its children is a layout like any
  other, and still the one `metadataBase` is read from for the sitemap.
- **`/` is a `route.ts`, not a page,** because a page that reads the request
  above every boundary has nothing to store and the build refuses it. A route
  that reads the request is answered per request and the build says so.
