Sub topic 14
Organising keys and catching missing translations
This chapter covers how to name and structure translation keys so a growing catalog stays manageable. It also covers how to detect missing or unused keys before users see them. It assumes you have a working react-i18next setup (see the setup and useTranslation chapters), you know how plural suffixes such as _one and _other work, and you can run npm scripts and a test runner such as Vitest.
Why key discipline matters
A catalog starts with five keys and grows to thousands. Without conventions, three problems appear:
- Two developers add
button.saveandcommon.savewith the same text, and translators pay for both. - A component is deleted but its keys stay in every language file forever.
- A new key is added to
en.jsononly, and German users see English text, or the raw key, in production.
Conventions and automated checks address each problem.
Naming keys
There are two common strategies.
| Strategy | Example | Strength | Weakness |
|---|---|---|---|
| Natural-language keys | `t('Save changes')` | Readable code, no catalog needed to understand it | Editing the English text changes the key. The same words can need different translations in different places. |
| Structured keys | `t('settings.profile.save')` | Stable ids, context is explicit | Code is less readable. Someone must invent names. |
Structured keys work better in teams. Follow these rules:
- Name by feature and role, not by wording. Use
cart.empty.title, notcart.yourCartIsEmpty. The text can change without renaming the key. - Group by screen or feature first. Use
checkout.*,settings.*, and a smallcommon.*group for truly shared words such as "Cancel". - Keep nesting shallow. Three levels is usually enough. Deeper trees are hard to scan in a diff.
- Describe the role in the last segment. Use
title,label,placeholder,error,cta. A translator can then see thatctais a button. - Never reuse a key for different meanings. English "Open" as a verb and as a status are different words in many languages. Use
door.actions.openandticket.status.open.
A catalog following these rules looks like this:
{
"common": {
"cancel": "Cancel"
},
"cart": {
"title": "Your cart",
"items_one": "{{count}} item in your cart",
"items_other": "{{count}} items in your cart",
"empty": {
"title": "Your cart is empty",
"cta": "Continue shopping"
}
}
}The plural suffix attaches to the last segment, so the code calls t('cart.items', { count }). The default key separator is .. If any of your keys or texts contain dots in the key itself, this nesting breaks, so avoid dots inside segment names.
Avoid dynamic key construction
This call looks harmless:
const label = t(`order.status.${status}`);Extraction tools read your source as text. They cannot know which values status takes, so they cannot see the keys order.status.shipped and order.status.pending. The extractor then reports those keys as unused, and cleanup deletes them. Use an explicit map instead, so every key appears literally in the source:
import type { TFunction } from 'i18next';
type Status = 'pending' | 'shipped';
export function statusLabel(t: TFunction, status: Status): string {
const labels: Record<Status, string> = {
pending: t('order.status.pending'),
shipped: t('order.status.shipped'),
};
return labels[status];
}The key lifecycle
Keys move through a loop: developers use them in code, a tool extracts them into catalogs, translators fill in the values, and CI verifies the result.
Extracting keys automatically
The i18next-parser package scans source files for t('...') calls and Trans usages. It adds new keys to each catalog and can remove keys that no longer appear. A minimal configuration, i18next-parser.config.js:
export default {
locales: ['en', 'de'],
defaultNamespace: 'translation',
output: 'src/locales/$LOCALE.json',
input: ['src/**/*.{ts,tsx}'],
keepRemoved: false,
sort: true,
};Add "i18n:extract": "i18next" to the scripts section of package.json. Running npm run i18n:extract then updates en.json and de.json.
Two behaviours to know:
- New keys are written with an empty string in non-default languages. Translators fill these in.
keepRemoved: falsedeletes keys the scanner cannot find. Combined with dynamic keys, this silently removes real translations, which is why the explicit-map pattern above matters. Review the diff of the catalog files in every pull request.
Type-checking keys at compile time
i18next can infer the valid keys from your English catalog, so a typo like t('cart.titel') becomes a TypeScript error. Enable "resolveJsonModule": true in tsconfig.json, then declare the resources:
// src/i18next.d.ts
import 'i18next';
import type en from './locales/en.json';
declare module 'i18next' {
interface CustomTypeOptions {
defaultNS: 'translation';
resources: {
translation: typeof en;
};
}
}This catches wrong keys and wrong interpolation names in the default language. It does not verify the other languages, so you still need a parity check.
Catching missing translations at runtime
During development you want a loud signal. In production you want a log entry and a safe fallback. i18next provides three options for this:
saveMissing: truemakes i18next call a handler when a key is missing in the requested language.missingKeyHandleris that handler.parseMissingKeyHandlerchanges the text returned for a key that is not found at all.
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import en from './locales/en.json';
import de from './locales/de.json';
const isDev = import.meta.env.DEV;
i18n.use(initReactI18next).init({
resources: { en: { translation: en }, de: { translation: de } },
lng: 'de',
fallbackLng: 'en',
returnEmptyString: false,
saveMissing: true,
missingKeyHandler: (lngs, ns, key) => {
const message = `Missing translation: ${lngs.join(',')}:${ns}:${key}`;
if (isDev) {
console.warn(message);
} else {
navigator.sendBeacon('/api/i18n-missing', message);
}
},
parseMissingKeyHandler: (key) => (isDev ? `⚠ ${key}` : key),
});
export default i18n;Notes on this configuration:
returnEmptyString: falsematters when the extraction tool writes empty strings. By default i18next treats""as a valid translation and shows a blank label. With the option set tofalse, an empty value counts as missing and falls back to English.- The handler runs for the requested language even when
fallbackLngsupplies text. A German user sees English, and you still get the report. - In production, deduplicate reports on the server. A popular page can send the same key thousands of times.
- The
⚠prefix in development makes untranslated keys stand out on screen. In production, showing the key itself is ugly, but showing English is better when the fallback exists.
Failing the build on missing keys
Runtime reports find problems after release. A CI test finds them before. This Vitest test checks that every language has the same keys as English. It strips plural suffixes, because languages need different plural categories (Arabic has _zero, _two, _few, _many, English has only _one and _other).
// src/locales/catalogs.test.ts
import { describe, expect, it } from 'vitest';
import en from './en.json';
import de from './de.json';
type Tree = { [key: string]: string | Tree };
const PLURAL = /_(zero|one|two|few|many|other)$/;
function flatten(tree: Tree, prefix = ''): string[] {
return Object.entries(tree).flatMap(([key, value]) =>
typeof value === 'string'
? [`${prefix}${key}`.replace(PLURAL, '')]
: flatten(value, `${prefix}${key}.`),
);
}
function values(tree: Tree): string[] {
return Object.values(tree).flatMap((v) => (typeof v === 'string' ? [v] : values(v)));
}
const base = new Set(flatten(en as Tree));
describe.each([['de', de as Tree]])('%s catalog', (_code, catalog) => {
const keys = new Set(flatten(catalog));
it('has every key that English has', () => {
const missing = [...base].filter((k) => !keys.has(k));
expect(missing).toEqual([]);
});
it('has no keys that English lacks', () => {
const extra = [...keys].filter((k) => !base.has(k));
expect(extra).toEqual([]);
});
it('has no empty values', () => {
expect(values(catalog).filter((v) => v.trim() === '')).toEqual([]);
});
});To cover more languages, add entries to the array passed to describe.each.
Common errors
- Reusing one key in two contexts. A later copy edit for one place changes both. Split the key when meanings differ.
- Keys defined only in the default language. The extractor hides this unless you run it in CI with
i18next --fail-on-update, which exits with an error when a catalog would change. - Splitting sentences across keys. Use one key per full sentence, with variables or
Transfor the dynamic parts. - Namespaces as a substitute for structure. Namespaces are for loading catalogs separately. They are not a naming tool. Keep one namespace until bundle size gives you a reason to split.
Exercise
A component calls t(filters.${name}.label), where name is one of "price", "brand" or "color". After running the extraction tool with keepRemoved set to false, the filters.price.label entries disappear from the catalogs. Why does this happen, and how do you fix it?
Show answer
The extractor reads source text and cannot evaluate the template literal, so it never sees the three concrete keys and treats the existing entries as unused. Fix it by writing each key literally, for example in a Record that maps "price", "brand" and "color" to t('filters.price.label'), t('filters.brand.label') and t('filters.color.label'). You can also set keepRemoved to true, but then genuinely unused keys are never cleaned up.
Exercise
Your German catalog contains "cart": { "title": "" }. With default i18next settings, what does the user see for t('cart.title'), and which option changes that so English is shown instead?
Show answer
The user sees an empty string, because i18next treats "" as a valid translation by default. Setting returnEmptyString to false makes it count the key as missing, so it calls missingKeyHandler and uses the fallback language (English).