Sub topic 16
Locale in URLs and Server Rendering
This chapter covers where the locale lives when your app is reachable by URL and rendered on a server. It assumes you know React hooks, the react-i18next setup from earlier chapters, and basic routing and Node concepts. Examples use React Router and a plain Node server with renderToString.
Why the URL should carry the locale
A client-only app can store the language in localStorage and read it on startup. That works for a logged-in user on one device. It fails in four cases:
- Search engines see one URL per page, so only one language gets indexed.
- A shared link opens in the recipient's language, not the sender's.
- A server cannot read
localStorage, so the first HTML it sends is in the wrong language. - Caches and CDNs cannot tell two language variants of one URL apart.
Putting the locale in the path, for example /de/cart, fixes all four. Each language variant gets its own URL that can be linked, cached and indexed.
URL strategies
| Strategy | Example | Notes |
|---|---|---|
| Path prefix | `example.com/de/cart` | Most common. Works on one host and one certificate. |
| Subdomain | `de.example.com/cart` | Needs DNS and certificate setup. Allows per-region hosting. |
| Country domain | `example.de/cart` | Strong regional signal, highest operational cost. |
| Query parameter | `example.com/cart?lang=de` | Easy, but weaker for search engines and easy to drop from links. |
This chapter uses the path prefix.
Treating the URL as the source of truth
Once the locale is in the URL, the URL decides the language. The language switcher navigates to a new URL. An effect then syncs i18next to the URL. Do not keep two sources of truth that can disagree.
Define the supported locales in one place and validate the URL segment against it.
export const SUPPORTED = ['en', 'de'] as const;
export type Locale = (typeof SUPPORTED)[number];
export const DEFAULT_LOCALE: Locale = 'en';
export function isLocale(value: string | undefined): value is Locale {
return SUPPORTED.some((code) => code === value);
}Routing with a locale segment
With React Router, nest every route under a /:locale segment. A layout component validates the segment, syncs i18next, and redirects when the segment is unknown.
import { useEffect } from 'react';
import { Navigate, Outlet, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { isLocale, DEFAULT_LOCALE } from './locales';
export function LocaleLayout() {
const { locale } = useParams();
const { i18n } = useTranslation();
const valid = isLocale(locale);
useEffect(() => {
if (valid && i18n.resolvedLanguage !== locale) {
void i18n.changeLanguage(locale);
}
}, [valid, locale, i18n]);
if (!valid) {
return <Navigate to={`/${DEFAULT_LOCALE}`} replace />;
}
return <Outlet />;
}Wire it into the router:
import { createBrowserRouter, Navigate } from 'react-router-dom';
import { LocaleLayout } from './LocaleLayout';
import { Cart } from './Cart';
export const router = createBrowserRouter([
{ path: '/', element: <Navigate to="/en" replace /> },
{
path: '/:locale',
element: <LocaleLayout />,
children: [{ path: 'cart', element: <Cart name="Ada" count={2} /> }],
},
]);The unknown-locale redirect above sends /fr/cart to /en, which loses the rest of the path. A more careful version keeps the remainder, but the principle is the same: never render with an unvalidated locale.
Switching by navigation
The language switcher from the earlier chapter now changes the URL instead of calling changeLanguage directly. The layout effect does the rest.
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { SUPPORTED } from './locales';
export function UrlLanguageSwitcher() {
const { locale } = useParams();
const { pathname, search } = useLocation();
const navigate = useNavigate();
function change(code: string) {
const rest = pathname.replace(/^\/[^/]+/, '');
navigate(`/${code}${rest}${search}`);
}
return (
<select value={locale} onChange={(e) => change(e.target.value)}>
{SUPPORTED.map((code) => (
<option key={code} value={code}>{code}</option>
))}
</select>
);
}The pathname.replace call swaps only the first segment. Query strings are carried over so filters survive the switch.
Choosing a locale for the bare URL
A visitor who opens / has no locale yet. Pick one in this order and stop at the first match:
- A saved user preference, such as a cookie set by the switcher.
- The
Accept-Languagerequest header, matched against your supported list. - The default locale.
Accept-Language looks like de-AT,de;q=0.9,en;q=0.5. Each entry has a quality value q, which defaults to 1. Match by language, not only by exact tag, so de-AT selects your de catalog.
import { DEFAULT_LOCALE, SUPPORTED, type Locale } from './locales';
export function pickLocale(header: string | undefined): Locale {
if (!header) return DEFAULT_LOCALE;
const ranked = header
.split(',')
.map((part) => {
const [tag, q] = part.trim().split(';q=');
return { tag: tag.toLowerCase(), q: q ? Number(q) : 1 };
})
.filter((entry) => entry.tag !== '*' && !Number.isNaN(entry.q))
.sort((a, b) => b.q - a.q);
for (const { tag } of ranked) {
const language = tag.split('-')[0];
const match = SUPPORTED.find((code) => code === language);
if (match) return match;
}
return DEFAULT_LOCALE;
}Use a redirect (HTTP 302) from / to the chosen locale. Use 302 and not 301, because the target depends on the visitor, and browsers cache 301 responses.
Server rendering
With server-side rendering (SSR), the server turns React components into an HTML string before sending the page. The browser shows content immediately, then React attaches event handlers in a step called hydration. For i18n, SSR raises two requirements.
- The server must render in the locale of the request.
- The client must start with the same locale and the same messages, or hydration produces mismatched text.
One i18next instance per request
The i18n singleton from the setup chapter is safe in the browser, where one user owns the page. On a server it is shared by all concurrent requests. If request A calls changeLanguage('de') while request B is rendering, B can come out in German. Create a fresh instance for each request.
import { createInstance } from 'i18next';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom/server';
import { App } from './App';
import { resources } from './resources';
import type { Locale } from './locales';
export async function render(url: string, locale: Locale) {
const i18n = createInstance();
await i18n.use(initReactI18next).init({
resources,
lng: locale,
fallbackLng: 'en',
interpolation: { escapeValue: false },
});
const html = renderToString(
<I18nextProvider i18n={i18n}>
<StaticRouter location={url}>
<App />
</StaticRouter>
</I18nextProvider>,
);
return { html, locale, messages: i18n.getResourceBundle(locale, 'translation') };
}I18nextProvider hands the per-request instance to useTranslation in the tree, so components need no changes.
Setting lang and dir in the HTML shell
An effect cannot set lang and dir on the server, because effects do not run during renderToString. Write them into the shell yourself, and pass the messages to the client so it hydrates with identical text.
import { createServer } from 'node:http';
import { render } from './render';
import { pickLocale } from './pickLocale';
import { isLocale } from './locales';
const RTL = new Set(['ar', 'he', 'fa', 'ur']);
function escapeJson(value: unknown): string {
return JSON.stringify(value).replace(/</g, '\\u003c');
}
createServer(async (req, res) => {
const url = req.url ?? '/';
const first = url.split('/')[1]?.split('?')[0];
if (!isLocale(first)) {
const locale = pickLocale(req.headers['accept-language']);
res.writeHead(302, { Location: `/${locale}${url === '/' ? '' : url}`, Vary: 'Accept-Language' });
res.end();
return;
}
const { html, locale, messages } = await render(url, first);
const dir = RTL.has(locale) ? 'rtl' : 'ltr';
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(`<!doctype html>
<html lang="${locale}" dir="${dir}">
<head><meta charset="utf-8" /><title>Shop</title></head>
<body>
<div id="root">${html}</div>
<script>window.__I18N__ = ${escapeJson({ locale, messages })};</script>
<script type="module" src="/client.js"></script>
</body>
</html>`);
}).listen(3000);Two details matter here. escapeJson replaces < so a message containing </script> cannot end the script tag early. The Vary: Accept-Language header tells caches that the redirect depends on that header.
Hydrating on the client
The client reads the embedded data and initialises with it, with no asynchronous load before the first render.
import { hydrateRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { createInstance } from 'i18next';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { App } from './App';
declare global {
interface Window {
__I18N__: { locale: string; messages: Record<string, string> };
}
}
const { locale, messages } = window.__I18N__;
const i18n = createInstance();
i18n.use(initReactI18next).init({
resources: { [locale]: { translation: messages } },
lng: locale,
fallbackLng: false,
interpolation: { escapeValue: false },
});
hydrateRoot(
document.getElementById('root')!,
<I18nextProvider i18n={i18n}>
<BrowserRouter>
<App />
</BrowserRouter>
</I18nextProvider>,
);Because resources is supplied inline, i18next initialises synchronously and the first client render matches the server HTML.
Search engine signals
Tell search engines how the language variants relate. In each page's <head>, list every variant with hreflang links, including the page itself and an x-default for the fallback:
<link rel="alternate" hreflang="en" href="https://example.com/en/cart" />
<link rel="alternate" hreflang="de" href="https://example.com/de/cart" />
<link rel="alternate" hreflang="x-default" href="https://example.com/en/cart" />Each page should also have a self-referencing <link rel="canonical">. Do not point the canonical of /de/cart to /en/cart, because that tells search engines the German page is a duplicate.
Common errors
- Hydration mismatch warnings. The server and client used different locales or catalogs. Embed the server's messages, as shown above, and check that the URL segment and the client locale agree.
- Wrong language under load. A shared i18next instance on the server. Use
createInstanceper request. - Lazy catalogs and SSR. A dynamic
import()that resolves afterrenderToStringreturns yields untranslated keys in the HTML. Load the needed catalog before rendering. dirmissing from server HTML. Effects do not run on the server. Setlanganddirin the shell.- Redirect loops. The layout redirects an invalid locale to a path that is itself invalid. Always redirect to a locale from your supported list.
- 301 on the bare URL. Browsers cache it and the visitor never sees a language change later.
Exercise
A server renders /de/cart correctly during testing, but under concurrent traffic some German visitors receive English text. The server imports the shared i18n singleton and calls i18n.changeLanguage(locale) at the start of each request. What is the cause and the fix?
Show answer
The singleton is shared by all in-flight requests. changeLanguage for one request changes the language that another request is rendering with, so the result depends on timing. Fix it by calling createInstance() for every request, initialising it with that request's locale, and passing it to the tree through I18nextProvider.
Exercise
A visitor opens / with the header Accept-Language: fr-CA,fr;q=0.9,de;q=0.8. Your supported locales are en and de, and the default is en. Which locale does pickLocale return, and which status code should the redirect use?
Show answer
It returns de. The entries are ranked fr-CA (q=1), fr (0.9), de (0.8). The first two have no matching catalog, so de is the first match. Use a 302 redirect, because the result depends on the request and a cached 301 would pin the visitor to one language.