Sub topic 16
Locale in URLs and server rendering
This chapter assumes you have react-i18next set up, can switch locale at runtime, and know React Router basics. You should also know what renderToString does.
Why put the locale in the URL
A locale kept only in component state or localStorage is invisible to crawlers, to link sharing, and to the server. A URL such as /de/cart fixes this. Each language gets its own address that can be bookmarked and indexed, and the server knows which language to render before any JavaScript runs.
There are three common patterns:
| Pattern | Example | Trade-off |
|---|---|---|
| Path prefix | `/de/cart` | Simple, works on one domain. Most common. |
| Subdomain | `de.example.com` | Needs DNS and certificate setup. |
| Country domain | `example.de` | Strongest regional signal, highest cost. |
This chapter uses the path prefix.
Routing by locale prefix
Make the first path segment a parameter. A layout route validates it and syncs i18next.
import { useEffect } from 'react';
import { Navigate, Outlet, useParams } from 'react-router-dom';
import i18n from './i18n';
const SUPPORTED = ['en', 'de'];
export function LocaleLayout() {
const { locale } = useParams();
const valid = locale !== undefined && SUPPORTED.includes(locale);
useEffect(() => {
if (valid) void i18n.changeLanguage(locale);
}, [locale, valid]);
if (!valid) return <Navigate to="/en" replace />;
return <Outlet />;
}Mount it as the parent of every page route, with the path /:locale. Links inside the app must keep the prefix, for example to={/${i18n.language}/cart}. A missing prefix on one link drops the user back to the default locale.
Rendering on the server
On the server, one Node process handles requests for many languages. The global i18n instance you export in the browser is shared state, so a concurrent request could change its language mid-render. Create a new instance per request instead.
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom/server';
import { I18nextProvider } from 'react-i18next';
import { createInstance } from 'i18next';
import { App } from './App';
export async function render(url: string, locale: string, messages: object) {
const instance = createInstance();
await instance.init({
lng: locale,
fallbackLng: 'en',
resources: { [locale]: { translation: messages } },
interpolation: { escapeValue: false },
});
const html = renderToString(
<I18nextProvider i18n={instance}>
<StaticRouter location={url}>
<App />
</StaticRouter>
</I18nextProvider>,
);
return { html, lang: locale, dir: instance.dir(locale) };
}The server writes lang and dir into the <html> tag of the response, so they are correct before hydration.
Common errors
- Hydration mismatch. If the client starts in a different language than the server rendered, React warns and text flickers. Initialise the client with the locale from the URL, and load its catalog before calling
hydrateRoot. - Shared server instance. Using the global instance on the server leaks one user's language into another's response.
- Redirect loops. When the root
/redirects byAccept-Language, make sure the target already carries a supported prefix. - Missing alternates. Add
<link rel="alternate" hreflang="de" href="https://example.com/de/cart">for each language, plusx-default. Search engines use these to show the right version.
Exercise
Why should a server-rendered app create a new i18next instance for each request instead of reusing the exported one?
Show answer
The server handles many requests concurrently, and the exported instance holds a single active language. A request for another locale could change that language while the first render is still running, so users would get pages in the wrong language. A per-request instance keeps each render isolated.