The challenge with i18n in SSR
Client-side i18n is straightforward: detect the locale from the browser, load the right resource bundle, render. SSR complicates this in two ways. First, the server has no access to the browser's language preference — it must infer locale from the URL. Second, whatever locale the server infers must be communicated to the client so both sides agree before hydration begins.
This project uses URL-prefixed locales (/en/about, /de/about) as the source of truth. A locale in the URL is unambiguous, works perfectly for SSR, is indexable by search engines with correct hreflang annotation, and degrades gracefully to a redirect when the bare path is requested.
Route structure
The router treats the locale segment as part of every route path. All application routes have two mirrors:
/en/ → Home (English)
/de/ → Home (German)
/en/posts → Blog list (English)
/de/posts → Blog list (German)
An explicit redirect from / to /en/ (or /de/ based on Accept-Language) handles bare paths. Search engines see two separate, fully localised URLs with matching <link rel="alternate" hreflang="..."> tags in the <head>.
Server-side locale detection
On the server, locale extraction is a simple string operation on the request URL:
const localeFromPath = req.path.split('/')[1];
const locale = ['en', 'de'].includes(localeFromPath) ? localeFromPath : 'en';
This locale is passed directly into the i18next instance before rendering. The i18next SSR flow looks like:
- Create a per-request i18next instance (avoid sharing state between requests)
- Set the locale from the URL
- Load the matching resource bundle (from disk on the server)
- Render the React tree with the i18next instance in context
Passing locale to the client
After rendering, the server embeds the detected locale into the HTML response — typically as a data attribute on <html lang="..."> combined with a serialized initial state object. The client reads this before initialising its own i18next instance:
const initialLocale = document.documentElement.lang || 'en';
await i18n.changeLanguage(initialLocale);
This ensures both sides use exactly the same locale for the initial render, preventing hydration mismatches in translated strings.
Locale-aware navigation
All internal links must preserve the current locale. A thin wrapper around the router's Link component adds the current locale prefix automatically:
function LocaleLink({ to, children }) {
const { i18n } = useTranslation();
return <Link to={'/' + i18n.language + to}>{children}</Link>;
}
This avoids having every call site know about the locale prefix, and makes switching locales a matter of changing the prefix in one place.
SEO: hreflang and canonical
Each page emits two <link rel="alternate" hreflang> tags and a <link rel="canonical"> pointing to the current-locale URL. Search engines use these to understand that /en/posts and /de/posts are translations of the same page, not duplicate content.