import { readFileSync } from "node:fs"; import path from "node:path"; import i18next, { type Resource, type ResourceLanguage } from "i18next"; import { formalLngs, i18nConfig, i18nNamespaces, supportedLocales } from "./i18n"; import { serverLocalePath } from "./i18next.server"; // The global instance must be able to render *and* `changeLanguage` into the // formal variants ("de-formal", "en-formal") in addition to the base locales. // Their bundles are loaded best-effort (missing files are non-fatal) and fall // back to the base locale for un-overridden keys. const globalLngs = [...supportedLocales, ...formalLngs]; /** * Server-side bootstrap for the *global* i18next instance (the default export * of `i18next`). A large number of components resolve translations through the * module-level `t` helper (`import { t } from "i18next"`) rather than the * `useTranslation()` hook. On the client that global instance is initialised in * `entry.client.tsx`, but on the server only the per-request scoped instance was * ever initialised. That left the global `t` returning empty strings during SSR, * which produced empty `sr-only` labels (axe `button-name`/`link-name` * violations) and — more damagingly — React hydration mismatches (error #418) * that aborted hydration and broke client interactivity on authenticated pages. * * Initialising the global instance with every locale preloaded synchronously, * then aligning its language with the request locale immediately before the * (synchronous) shell render, keeps SSR output identical to the hydrated client * output. The language is mutated per request; because the non-streaming shell * render that follows `syncServerGlobalI18nLanguage` is synchronous, the global * language is correct for that render. */ function loadAllResources(): Resource { const resources: Resource = {}; for (const locale of globalLngs) { const bundle: ResourceLanguage = {}; for (const namespace of i18nNamespaces) { try { const file = path.join(serverLocalePath, locale, `${namespace}.json`); bundle[namespace] = JSON.parse(readFileSync(file, "utf8")) as ResourceLanguage[string]; } catch { // A missing namespace file is non-fatal: i18next will fall back to the // fallback language / key for that namespace. This is also the path the // formal variants take until their override files exist on disk. bundle[namespace] = {}; } } resources[locale] = bundle; } return resources; } function registerAllBundles(resources: Resource): void { // Register every locale/namespace bundle. `init({ resources })` only // guarantees the active language's bundle is added; registering them all // up-front lets `changeLanguage` resolve any supported locale synchronously. // This also backfills bundles when another module (e.g. test setup) already // initialised the global instance with a narrower resource set. for (const locale of Object.keys(resources)) { for (const namespace of Object.keys(resources[locale]!)) { if (!i18next.hasResourceBundle(locale, namespace)) { i18next.addResourceBundle(locale, namespace, resources[locale]![namespace], true, true); } } } } let initPromise: Promise | null = null; export async function ensureServerGlobalI18n(): Promise { if (i18next.isInitialized) { registerAllBundles(loadAllResources()); return i18next; } if (!initPromise) { const resources = loadAllResources(); initPromise = i18next .init({ ...i18nConfig, // Accept the formal variants as valid languages so a later // `changeLanguage("-formal")` is honoured instead of being // dropped back to the detection fallback. supportedLngs: globalLngs, lng: i18nConfig.fallbackLng, preload: [...globalLngs], resources, // Resources are bundled in memory, so no backend/async loading is needed. initImmediate: false, }) .then(() => { registerAllBundles(resources); return i18next; }); } return initPromise; } export async function syncServerGlobalI18nLanguage(language: string): Promise { await ensureServerGlobalI18n(); if (i18next.language !== language) { await i18next.changeLanguage(language); } }