React localization with i18next and Localeo
Wire a React app built with Vite to a Localeo release using i18next and react-i18next. You’ll use Localeo’s JSON files, download them at build time so they ship inside your bundle, and optionally load the latest release at runtime instead.
- Framework
- React 19.3 + Vite 8, i18next 27, react-i18next 18
- Format
- JSON
- Time
- 15 minutes
Find your release files
In Localeo, open your project and go to Releases. Every published release has a download link per language and format, and there is also a
latestlink that always points at the newest published release. You’ll use the JSON links:bash # a pinned release: never changes, cached for a yearhttps://cdn.localeo.app/p/<projectSlug>/r/<releaseSlug>/<lang>.json # the newest published release: cached for about a minute, refreshed on publishhttps://cdn.localeo.app/p/<projectSlug>/r/latest/<lang>.jsonEach file is a flat JSON object keyed by your keys exactly as you wrote them. Keys often contain dots, but they are not nested:
nl.json { "app.title": "Acme Winkel", "cart.greeting": "Hoi {name}, welkom terug!", "cart.items": "{count, plural, one {# artikel} other {# artikelen}}", "checkout.pay_button": "Nu {amount} betalen"}A key with no translation in a language is left out of that language’s file, so your app needs to fall back to the base language. A publish includes every value, drafts too.
Install i18next with ICU support
bash npm install i18next react-i18next i18next-icu intl-messageformat i18next-resources-to-backendLocaleo placeholders use single braces (
{name}), while i18next expects{{name}}by default. You can change i18next’s interpolation prefix and suffix to single braces, but that only fixes simple placeholders: in our tests it turned{count, plural, one {# item} other {# items}}into5 other {# items}}.i18next-icuswaps i18next’s own format for ICU MessageFormat, so placeholders and plurals both render as written in Localeo.Download a release at build time
Put the CDN base, your project slug and the release slug in
.env. Pin a release slug for reproducible builds;latestworks too if you’d rather pick up whatever was published last each time you build..env LOCALEO_CDN_URL=https://cdn.localeo.appLOCALEO_PROJECT=<projectSlug>LOCALEO_RELEASE=<releaseSlug>A small Node script saves one file per language into
src/locales/. These variables have noVITE_prefix, so Vite never puts them in your bundle.scripts/fetch-locales.mjs // Downloads a Localeo release into src/locales/, so it ships inside the bundle.import { mkdir, writeFile } from "node:fs/promises"; const LANGUAGES = ["en", "nl", "pt-BR"]; // keep in sync with src/i18n.ts const { LOCALEO_CDN_URL, LOCALEO_PROJECT, LOCALEO_RELEASE } = process.env;if (!LOCALEO_CDN_URL || !LOCALEO_PROJECT || !LOCALEO_RELEASE) { throw new Error("Set LOCALEO_CDN_URL, LOCALEO_PROJECT and LOCALEO_RELEASE");}const release = `${LOCALEO_CDN_URL}/p/${LOCALEO_PROJECT}/r/${LOCALEO_RELEASE}`; await mkdir("src/locales", { recursive: true });await Promise.all( LANGUAGES.map(async (lang) => { const res = await fetch(`${release}/${lang}.json`); // Only the file name: the URL contains your project slug. if (!res.ok) throw new Error(`${lang}.json: HTTP ${res.status}`); await writeFile(`src/locales/${lang}.json`, await res.text()); }),);Run it before every dev server start and every build:
package.json "scripts": { "locales": "node --env-file-if-exists=.env scripts/fetch-locales.mjs", "predev": "npm run locales", "dev": "vite", "prebuild": "npm run locales", "build": "tsc -b && vite build"}Configure i18next for flat keys and ICU
src/i18n.ts import i18n from "i18next";import ICU from "i18next-icu";import resourcesToBackend from "i18next-resources-to-backend";import { initReactI18next } from "react-i18next"; export const BASE_LANGUAGE = "en"; // your Localeo project's base languageexport const LANGUAGES = ["en", "nl", "pt-BR"]; i18n .use(ICU) // Localeo values use {name} and ICU plurals .use(resourcesToBackend((lang: string) => import(`./locales/${lang}.json`))) .use(initReactI18next) .init({ lng: BASE_LANGUAGE, fallbackLng: BASE_LANGUAGE, supportedLngs: LANGUAGES, load: "currentOnly", // load pt-BR, not pt-BR + pt keySeparator: false, // "cart.items" is one flat key, not cart → items nsSeparator: false, // keys may contain ":" }); i18n.on("languageChanged", (lang) => { document.documentElement.lang = lang;});fallbackLngis your Localeo base language. Whenpt-BR.jsonhas nocheckout.pay_button, i18next uses the English value.nsSeparator: falseis required if any key contains a colon. Without it, i18next readserrors:networkas keynetworkin a namespace callederrorsand returns the wrong string.keySeparator: falsetells i18next not to treat dots as nesting. i18next’s flat-key fallback happens to find dotted keys anyway, but this makes the lookup direct.load: "currentOnly"stops i18next from also requesting aptfile that Localeo doesn’t produce.
The dynamic
import()makes Vite emit one small chunk per language, so users only download the language they’re looking at.Translate in your components
Import the config once, and wrap the app in
Suspense, since react-i18next suspends while a language file loads.src/main.tsx import { StrictMode, Suspense } from "react";import { createRoot } from "react-dom/client";import "./i18n";import App from "./App"; createRoot(document.getElementById("root")!).render( <StrictMode> <Suspense fallback={null}> <App /> </Suspense> </StrictMode>,);Then call
twith your Localeo keys, passing placeholder values and the plural count as options:src/App.tsx import { useState } from "react";import { useTranslation } from "react-i18next";import { LANGUAGES } from "./i18n"; export default function App() { const { t, i18n } = useTranslation(); const [count, setCount] = useState(1); return ( <main> <select value={i18n.resolvedLanguage} onChange={(e) => i18n.changeLanguage(e.target.value)} > {LANGUAGES.map((lang) => ( <option key={lang}>{lang}</option> ))} </select> <h1>{t("app.title")}</h1> <p>{t("cart.greeting", { name: "Sam" })}</p> <p>{t("cart.items", { count })}</p> <button type="button" onClick={() => setCount((c) => c + 1)}> +1 </button> <button type="button"> {t("checkout.pay_button", { amount: "€12.50" })} </button> </main> );}In Dutch this renders “Hoi Sam, welkom terug!”, then “1 artikel” or “5 artikelen”. In Brazilian Portuguese the pay button reads “Pay €12.50 now”, because that key is missing from
pt-BR.jsonand falls back to English.Or load the latest release at runtime
Bundling a pinned release gives you reproducible builds: what you tested is what ships. The trade-off is that a copy change needs a rebuild. If you’d rather pick up new translations without redeploying, fetch the
latestfiles in the browser withi18next-http-backend. They’re cached for about a minute, so a publish shows up shortly after.bash npm install i18next-http-backendIn
src/i18n.ts, replace theresourcesToBackendline with.use(HttpBackend)and add abackendoption. The rest stays the same:src/i18n.ts import HttpBackend from "i18next-http-backend"; i18n .use(ICU) .use(HttpBackend) .use(initReactI18next) .init({ // ...same options as before, plus: backend: { loadPath: "/locales/{{lng}}.json", // proxied to the CDN, see vite.config.ts }, });The
{{lng}}placeholder belongs to the backend plugin, so it keeps its double braces even with ICU enabled. The path points at your own origin, and Vite proxies it to Localeo’slatestfiles:vite.config.ts import react from "@vitejs/plugin-react";import { defineConfig, loadEnv } from "vite"; export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd(), "LOCALEO_"); // server-side only, never in the bundle const proxy = { "/locales": { target: env.LOCALEO_CDN_URL, changeOrigin: true, rewrite: (path: string) => path.replace(/^\/locales/, `/p/${env.LOCALEO_PROJECT}/r/latest`), }, }; return { plugins: [react()], server: { proxy }, preview: { proxy } };});That covers
npm run devandnpm run preview. In production, set up the same rewrite on whatever serves your app:/locales/*tohttps://cdn.localeo.app/p/<projectSlug>/r/latest/*. Most static hosts and reverse proxies support this. As a bonus, the project slug stays out of your JavaScript.Next steps
- Read how releases, the
latestlink and caching work in Releases and bundles. - Using pinned releases? Subscribe to the
release_publishedwebhook and trigger a rebuild in CI, so a publish in Localeo ends up in your next deploy without anyone copying files around. - Adding a language in Localeo? Add it to
LANGUAGESin bothscripts/fetch-locales.mjsandsrc/i18n.ts.
- Read how releases, the
Ship it with Localeo
Create a project, add your languages and publish your first release. Then point this setup at its links.
Get started