Next.js
Under Next.js’s App Router the locale is the first segment of the URL too. Put the root layout at app/[locale]/layout.tsx with one LocaleProvider from @k8ordo/i18n/next, and the messages of Server Components and Client Components will render in the URL’s locale.
On this page
The root layout
src/app/[locale]/layout.tsximport { LocaleProvider } from '@k8ordo/i18n/next';
import type { ReactNode } from 'react';
import { Providers } from '../../components/providers';
import { locales } from '../../i18n';
export const generateStaticParams = () =>
locales.all.map((locale) => ({ locale }));
export default function RootLayout({ children }: { children: ReactNode }) {
const locale = locales.getLocale();
return (
<html dir={locales.definitions[locale].dir} lang={locale}>
<body>
<LocaleProvider>
Hands the locale to the Client Components below
<Providers>{children}</Providers>
</LocaleProvider>
</body>
</html>
);
}@k8ordo/i18n/next reads the locale from next/root-params, which Next.js 16.3 and later provide. Root params are the root layout’s parameters, so make app/[locale]/layout.tsx the root layout and write no app/layout.tsx.
Wrap <body>’s children in LocaleProvider, once. Return locales.all from generateStaticParams to write each locale’s pages statically.
src/components/providers.tsx'use client';
import type { ReactNode } from 'react';
import '../i18n';
export function Providers({ children }: { children: ReactNode }) {
return children;
}For the browser to define the set too, import src/i18n.ts from a Client Component the layout renders. Without it, a message called in the browser throws message: no locale set is defined in this browser.
Note
LocaleProvider only hands a value down. Next.js renders a layout and its page side by side, so there is no other way for the layout’s locale to reach the page’s Client Components. @k8ordo/framework reads the locale before it renders anything, so it has no provider.
Async Server Components
src/app/[locale]/news/page.tsximport { accept } from '@k8ordo/i18n/next';
import type { Metadata } from 'next';
import { loadNews } from '../../../lib/news';
import { count, documentTitle, title } from '../../../messages/news';
export const generateMetadata = async (): Promise<Metadata> => {
await accept();
return { title: documentTitle() };
};
export default async function NewsPage() {
await accept();
Before anything else
const news = await loadNews();
return (
<>
<h1>{title()}</h1>
<p>{count(news.length)}</p>
</>
);
}A Server Component that is not async, and a Client Component, call messages with nothing written. The page stays static.
An async Server Component and generateMetadata write await accept() first. A message reads the locale through React’s use(), which is not available after an await. accept() reads it once for the request, and every message after it uses that value.
Pitfall
Forgotten, the text after an await throws an error starting @k8ordo/i18n/next: text was read after an await. A message read before the first await can stop the response with no error at all. Write accept() first in the function.
Another component’s accept() in the same request can hide a missing one, so each async component writes its own.
Client Components and switching
A Client Component reads the locale LocaleProvider hands it: through context on the server, and in the browser the locale LocaleProvider last rendered.
The browser does not read the URL, because Next.js keeps it on the page being left while it renders the next one. Following a next/link to another locale switches every text, @k8ordo/ui’s and @k8ordo/form’s built-in words included.
src/components/locale-switch.tsx'use client';
import type { Route } from 'next';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { locales } from '../i18n';
export function LocaleSwitch() {
const pathname = usePathname();
return locales.all.map((locale) => (
<Link
href={locales.localize(pathname, locale) as Route}
hrefLang={locale}
key={locale}
lang={locale}
>
{locale}
</Link>
));
}A language switcher is a next/link to the pathname usePathname() returns, taken to another locale with locales.localize.
Server Actions and Route Handlers
src/app/[locale]/contact/page.tsx<ContactForm
action={sendContact.bind(null, locales.getLocale())}
fields={formFields(contactForm)}
/>src/lib/contact-actions.ts'use server';
import { parseForm } from '@k8ordo/form/server';
import { locales } from '../i18n';
import { contactForm } from './contact-definition';
export async function sendContact(
locale: string,
_previous: ContactState,
formData: FormData,
): Promise<ContactState> {
return locales.run(locales.is(locale) ? locale : locales.default, () => {
Checked again: it came back from the browser
const parsed = parseForm(contactForm, formData);
return parsed.success ? { accepted: true } : parsed.state;
});
}Server Actions and Route Handlers run outside a render, and Next.js gives them no root params. The page binds its locale to the action, and the action calls its messages inside locales.run.
Text read outside run is the default locale’s. Calling accept() here throws an error starting accept: not inside a Server Component render.
/ and locales outside the set
src/proxy.tsimport { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { locales } from './i18n';
export function proxy(request: NextRequest): NextResponse {
return NextResponse.redirect(
new URL(`/${locales.negotiateRequest(request)}`, request.nextUrl),
);
}
export const config = { matcher: '/' };/ is redirected by the proxy to the locale negotiateRequest picks. How it picks is covered in Negotiation.
A [locale] outside the set is notFound(), so /fr/… answers 404. locales.params is @k8ordo/framework’s declaration and has no part here.