Sub topic 14
Organising keys and catching missing translations
This chapter assumes you have react-i18next set up, as in the earlier chapters. You should know t(), plural suffixes such as _one and _other, and how a JSON catalog is loaded. Here you will name keys so they stay stable, then add checks that catch gaps before users do.
Naming keys
A key is an identifier, not the English text. If the key is the English sentence, any copy edit changes the key in every catalog. Use a stable, descriptive path instead.
- Group by feature or screen:
cart.title,checkout.payButton. - Name the role of the text, not its wording:
checkout.payButton, notcheckout.payNow. - Keep one style, such as camelCase, across the whole project.
- Do not reuse a key for two meanings. "Open" as a verb and "Open" as a status are different words in many languages.
{
"cart": {
"title": "Your cart",
"empty": "Your cart is empty",
"items_one": "{{count}} item in your cart",
"items_other": "{{count}} items in your cart"
},
"checkout": {
"payButton": "Pay now"
}
}i18next treats . as the key separator by default, so t('cart.title') reads the nested value. For large apps, split catalogs into namespaces, one file per feature, so each feature loads only its own text.
Finding missing translations at runtime
When a key has no value in the active language or the fallback, i18next returns the key itself. That string is easy to miss in a code review. In development, make the failure loud.
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n.use(initReactI18next).init({
resources: { en: { translation: { cart: { title: 'Your cart' } } } },
lng: 'en',
fallbackLng: 'en',
saveMissing: true,
missingKeyHandler: (languages, namespace, key) => {
console.warn(`Missing translation: ${namespace}:${key} (${languages.join(', ')})`);
},
parseMissingKeyHandler: (key) => `⚠ ${key}`,
});missingKeyHandler only runs when saveMissing is true. parseMissingKeyHandler changes what the user sees, so placeholders like ⚠ cart.empty stand out on screen.
Checking catalogs in CI
A runtime warning only fires for screens someone opens. A script that compares catalogs checks everything. This one treats English as the source of truth and ignores plural suffixes, because languages need different plural forms. German needs two, and Arabic needs six.
import { readFileSync } from 'node:fs';
type Tree = { [key: string]: string | Tree };
const PLURAL_SUFFIX = /_(zero|one|two|few|many|other)$/;
function flatten(tree: Tree, prefix = ''): string[] {
return Object.entries(tree).flatMap(([key, value]) =>
typeof value === 'string' ? [prefix + key] : flatten(value, `${prefix}${key}.`),
);
}
function baseKeys(file: string): Set<string> {
const tree = JSON.parse(readFileSync(file, 'utf8')) as Tree;
return new Set(flatten(tree).map((key) => key.replace(PLURAL_SUFFIX, '')));
}
const source = baseKeys('src/locales/en.json');
let failed = false;
for (const code of ['de']) {
const target = baseKeys(`src/locales/${code}.json`);
const missing = [...source].filter((key) => !target.has(key));
const unused = [...target].filter((key) => !source.has(key));
if (missing.length > 0) {
failed = true;
console.error(`${code}: missing ${missing.join(', ')}`);
}
if (unused.length > 0) {
console.warn(`${code}: not in source ${unused.join(', ')}`);
}
}
process.exit(failed ? 1 : 0);Run it with a TypeScript runner such as npx tsx scripts/check-i18n.ts in your CI pipeline. A non-zero exit code fails the build when a translation is missing.
Keeping keys and code in sync
Catalogs and code drift apart. A tool such as i18next-parser scans your source for t('...') calls and adds new keys to the catalogs. It can also report keys that no code uses. Run it before each release so dead strings do not pile up.
Exercise
A German catalog has cart.items_one and cart.items_other. The English catalog also has both. Why does the comparison script strip the plural suffix before comparing?
Show answer
Languages need different plural categories. A language such as Arabic needs _zero, _two, _few and _many that English does not have. Comparing the base key cart.items checks that the message exists without requiring the same suffixes in every language.