Skip to main content

Lazy-Load Translation Files Without Stale Strings After Deploys

2026-12-01

Lazy-Load Translation Files Without Stale Strings After Deploys

You moved translations out of the main bundle so a German visitor no longer downloads Japanese, Arabic, and Thai. The first release after that change goes out, and returning users start reporting buttons that read items.new or popups that show {{neighborhood}} instead of a place name. A hard refresh fixes it for them, which tells you exactly what happened: the new code is running against an old dictionary.

This guide shows how to lazy load translations so the first download stays small and every deploy still serves matching strings. It covers what to bundle and what to fetch, how to version translation files with the build, which cache headers to set, which caches ignore those headers, and how to test the whole thing before users do.

The short answer

  1. Bundle the source language and your fallback language. Fetch everything else per locale and per namespace.
  2. Give every translation file a URL that changes when its content changes: a content hash in the filename, or a build id in the query string.
  3. Serve versioned files with a long max-age and immutable. Serve anything unversioned with no-cache so it is revalidated.
  4. Bump the version of every client-side cache layer (localStorage backend, service worker) with each build.
  5. Ship new keys before the code that uses them, and remove old keys only after the code that used them is gone.
  6. Add a deploy test that loads the previous dictionary with the new code and fails on raw keys.

Why stale translation files show raw keys

Bundlers fingerprint the code they build. Your main.3f9c1a.js gets a new name on every release, so browsers fetch it fresh. Translation files loaded at runtime usually sit outside that pipeline, at a fixed path such as /locales/de/translation.json. The browser has no way to know that file belongs to a specific release.

Without explicit headers, the browser and any proxy fall back to heuristic freshness, so the old file can be reused for hours. The store-it maintainers found exactly this in September 2026: nginx served /assets/i18n/*.json with no Cache-Control, so returning browsers kept the previous dictionary after every release and showed the raw key items.new for a string that existed in all four language files. That report is one team's account, but the mechanism is general HTTP caching.

The Project Sidewalk issue from the same month describes the sharper version. JavaScript was fingerprinted, but public/locales/<lng>/<ns>.json was not, because i18next-http-backend builds its own URLs from loadPath. Right after a deploy, returning visitors got the new JS with old translation files for up to an hour. Any renamed key showed as a raw key name, and any renamed interpolation variable showed as a literal {{neighborhood}}.

The same question has been asked on Stack Overflow for years. A 2017 question about disabling caching for i18next translation.json, viewed more than 21,000 times, describes users seeing the key instead of the text after new keys were added. Another asker found old JSON cached after updates and settled on cache: 'no-store', and a third asked how to add a hash to files under public/locales the way the build already does for code.

Version skew is the real bug

Most advice stops at "turn off caching", which hides the symptom. The bug underneath is version skew, where two artifacts from different releases run together. The code and the dictionary form one contract (key names, placeholder names, namespace names), and the contract changes in some releases.

Fallback languages do not fix this. If de is stale and the key is missing there, i18next falls back to en, so German users see English instead of a raw key. That looks better in a screenshot and hides the bug from monitoring. Our article on fallback languages explains how fallback chains behave; treat a spike in fallback hits right after a deploy as a version-skew alarm, not a translation gap.

So the decision rule is: every translation file the app can request must be tied to a build id, the same way the code is. Once that is true, the cache can be as aggressive as you like. Put plainly, hashed JavaScript plus unversioned locale JSON creates version skew after every deploy: new code asks for keys the cached dictionary lacks, so version dictionaries with the same build id as the code and ship additive key changes before removals.

Decide what to bundle and what to lazy load

Lazy loading has a cost. Each fetched file is a network round trip that blocks text from rendering. Bundling has a cost too: the worldmonitor team reported in July 2026 that one dependency chunk statically included about 28 locales at 24 to 40 KB each, while a visitor needs one locale plus the English fallback. Their estimate was 200 to 300 KB of avoidable payload on the common path.

Use these rules:

  • Bundle the source language and the fallback language. They are needed for every visitor, including the moment a lazy fetch fails.
  • Lazy load every other locale, fetched once the active language is known.
  • Split by namespace only when a feature's strings are large and rarely seen, such as an admin console or an onboarding flow most users finish once.
  • Do not split tiny namespaces. Ten 2 KB requests cost more than one 20 KB request.

i18next supports mixing the two. The i18next guide to adding or loading translations documents partialBundledLanguages: true, which lets you pass some resources at init while a backend loads the rest. It also points to i18next-resources-to-backend, which turns bundler imports into a backend so locale files go through the normal build and get hashed names.

import i18next from 'i18next';
import resourcesToBackend from 'i18next-resources-to-backend';
import en from './locales/en/translation.json';

i18next
  .use(resourcesToBackend((lng, ns) => import(`./locales/${lng}/${ns}.json`)))
  .init({
    lng: detectedLanguage,
    fallbackLng: 'en',
    partialBundledLanguages: true,
    resources: { en: { translation: en } },
  });

Here en ships in the entry chunk. Every other locale becomes its own chunk with a content hash in its filename, so the version problem disappears for these files: a changed dictionary gets a new URL.

Vue I18n's lazy-loading guide uses the same pattern: a dynamic import() of ./locales/${locale}.json, then setLocaleMessage before switching the locale. In Vite, import.meta.glob returns a map of lazy import functions, one chunk per file, unless you pass { eager: true }, which pulls them all into the importing chunk.

Check what the browser actually fetches

A template-literal import does not prove what the browser downloads. The bundler sees ./locales/${lng}.json, emits a chunk for every file that matches, and some setups then add prefetch hints for all of them. One Vue CLI user found every locale downloading on page load even though only one import ever ran. The import code was lazy, but the build still downloaded every chunk. A template-literal dynamic import tells the bundler to emit a chunk for every matching locale file, and some build setups then prefetch all of them, so check the network panel for what is actually fetched instead of trusting that the code is lazy.

The check takes two minutes. Open the network panel with cache disabled, load the app in one language, and count the locale files requested. Then switch language and confirm exactly one new file arrives. Repeat this after any bundler upgrade, because prefetch defaults change between versions. If you see every locale on first load, look for prefetch or preload link injection in your build tool's settings before you rewrite any i18n code.

Version runtime-fetched translation files with the build

Bundler imports are not always possible. Translators may update files on a CDN between releases, or a translation management system may push files to a bucket. In those cases the app fetches JSON from a path, and you need to put the version into the URL yourself.

The i18next-http-backend README documents queryStringParams, which appends parameters to each resource URL. Its own example turns example.com into example.com?v=1.3.5. Set it from a build-time constant, not from Date.now(), which would defeat caching entirely.

import HttpBackend from 'i18next-http-backend';

i18next.use(HttpBackend).init({
  fallbackLng: 'en',
  backend: {
    loadPath: '/locales/{{lng}}/{{ns}}.json',
    queryStringParams: { v: import.meta.env.VITE_BUILD_ID },
  },
});

A query string works when every file changes together. When translation files are published independently of code, use a manifest instead: the deploy step writes locales-manifest.json mapping each lng/ns pair to a hashed filename, and loadPath becomes a function that reads it. The manifest itself is small and served with no-cache.

Release order for key and placeholder changes

Versioning removes most skew, but not all of it. A user can keep a tab open across a deploy, and the old code in that tab will fetch a dictionary when they switch language. Plan key changes the way you would plan a database migration:

  1. Add first. Ship new keys and new placeholder names in the dictionaries, with old keys still present.
  2. Switch code. Deploy code that uses the new keys.
  3. Remove later. Delete old keys a release or two afterward, once no live code reads them.

This is a recommendation from first principles rather than a documented library rule, but it is what the Project Sidewalk report implies: renaming a key or an interpolation variable in one step is what turned stale dictionaries into visible raw keys and literal placeholders. Keep the old keys until your analytics show no sessions on the release that used them.

Set cache headers per asset class

Once URLs carry versions, headers become simple. web.dev's HTTP caching guide recommends a one-year max-age for fingerprinted or versioned URLs and revalidation for URLs that do not change when content changes. MDN's Cache-Control reference describes immutable for exactly this case: a response that will never change while fresh, with updates delivered under a new URL.

Asset Example Cache-Control
Hashed locale chunk /assets/de-8a1f2c.js public, max-age=31536000, immutable
JSON with build id /locales/de/app.json?v=2026.10.29 public, max-age=31536000, immutable
Unversioned JSON /locales/de/app.json no-cache
Locale manifest /locales-manifest.json no-cache
HTML entry /index.html no-cache

no-cache does not mean "never store". It means the browser must revalidate with the server before reuse, which costs a small request but returns a 304 when nothing changed. That is the right default for anything whose URL stays the same across releases. The store-it fix used exactly this split: no-cache for the dictionaries, immutable for hashed JS.

Avoid no-store on translation files as a permanent fix. It forces a full download on every page load, and on slow connections that delay is visible as untranslated or flickering text.

The query-string approach has one trap. If an older release already served the JSON without any header, browsers may still hold that copy under the bare URL. The store-it team added a per-start query stamp on the client for this reason, because a header change only affects responses fetched after it ships.

Clear the caches that ignore your headers

HTTP headers govern the browser's HTTP cache and well-behaved proxies. Three other places can keep an old dictionary, and none of them reads Cache-Control from your translation response.

The localStorage backend. The i18next caching guide shows a chained backend that reads from i18next-localstorage-backend first and falls back to HTTP, with an example expirationTime of seven days. That means a stored dictionary is served from localStorage for up to a week without any network request. The i18next-localstorage-backend README documents the way out: a versions object or a getVersion function. When the stored version differs from the configured one, the cached entry is ignored. The default defaultVersion is an empty string, so if you never set it, a new release does not invalidate anything.

backendOptions: [
  {
    expirationTime: 7 * 24 * 60 * 60 * 1000,
    defaultVersion: import.meta.env.VITE_BUILD_ID,
  },
  { loadPath: '/locales/{{lng}}/{{ns}}.json', queryStringParams: { v: import.meta.env.VITE_BUILD_ID } },
],

Use the same build id for both layers so they cannot disagree.

The service worker. If your service worker precaches /locales/**, the precache manifest needs the translation files with their revisions, or the worker will keep serving the old copy until it updates. Treat locale files like any other precached asset.

The CDN. A CDN that caches unversioned JSON for an hour will serve stale files to everyone, regardless of what the browser does. Either version the URLs or purge the locale path as part of the deploy job.

It is easy to fix the header, test in a fresh browser, see correct strings, and close the ticket while returning users with a warm localStorage cache keep seeing the old copy for days. When you test a caching fix, test with a browser profile that loaded the previous release. A correct Cache-Control header does not clear every stale copy, because a CDN, a service worker, or i18next-localstorage-backend can each keep the old dictionary; bump the localStorage backend's versions with each build and purge or version the other layers too.

Handle the loading state without flicker

Lazy loading means text can be requested before its dictionary arrives. react-i18next's useTranslation hook suspends while translation files are pending, so a Suspense boundary with a fallback covers it. If you turn off Suspense, the docs say you must handle the not-ready state yourself; rendering before the files load causes missing-key handling to fire for keys that exist but have not loaded yet.

If you log missing keys to find untranslated strings, a race between render and fetch fills your logs with false positives. Gate rendering on ready, or exclude events that occur before the namespace load resolves.

Where you place the boundary decides what users see. One developer reported a page flicker when a collapsible section needed a namespace that had not loaded, because the suspension reached a boundary high in the tree. Put a boundary close to the lazily loaded feature, or preload that namespace when the user hovers or focuses the control that opens it. For a language switch, fetch the new locale first and change the language only after it resolves, which is what Vue I18n's loadLocaleMessages pattern does.

Verify the fix with a deploy test

Unit tests run against one set of files, so they cannot catch version skew. Add a test that reproduces a deploy:

  1. Build release N and release N+1, where N+1 adds a key and renames one placeholder.
  2. Serve N+1 code with N's translation files, under the headers you plan to ship.
  3. Load each supported locale and scan the rendered DOM for raw key patterns (such as ^[a-z]+(\.[a-z-]+)+$) and leftover {{ or }}.
  4. Expect the scan to fail. Then serve N+1 code with N+1 files and expect zero matches.
  5. Repeat with a warm localStorage cache from release N, and with the service worker installed.

The first run proves the test can see the bug. The second proves the versioning fix works. Also assert the network counts from the bundle check: one locale file on first load, one more per language switch.

In production, watch three numbers for an hour after each release: missing-key events, fallback-language hits, and 404s on locale paths. A rise in any of them right after a deploy points to skew rather than a translation gap.

Common mistakes

  • Using Date.now() as the cache buster. Every page load downloads every dictionary again. Use the build id.
  • Fixing headers but not localStorage. Returning users keep a week-old copy. Set defaultVersion or versions.
  • Renaming a key and its usage in one release. Open tabs and cached files break. Add, switch, then remove.
  • Treating fallback text as success. English on a German page after a deploy is the same bug as a raw key.
  • Trusting that import() is lazy. Check the network panel after every bundler change.

Next step

Open your production app in a browser profile that visited before the last release, and look at the response headers and storage for your current locale's translation file. If its URL has no version, its Cache-Control is missing, or a localStorage entry predates the deploy, add a build id to loadPath and to the localStorage backend's defaultVersion this week, then run the N versus N+1 deploy test before the next release.