Sub topic 2
Locales and language tags
This chapter assumes you can write React function components and hooks, and that you have read the previous chapter on what internationalisation involves. By the end you will be able to read and validate a language tag, tell a language from a locale, and choose a fallback strategy. The later chapters on react-i18next, plurals and formatting all depend on this.
Language, region and locale
A language is what the text is written in, such as German. A region is a place whose conventions differ from other places that speak the same language, such as Austria or Switzerland. A locale is the combination of the two, plus any preferences that affect formatting. German in Austria (de-AT) and German in Switzerland (de-CH) share most of their vocabulary. They still differ in details such as the thousands separator and some spellings.
A locale controls two things:
- Which translated text the user reads.
- How values are formatted: numbers, currencies, dates, lists and plural rules.
These two can come apart. A user may want French text but prices formatted for Canada. Keep that in mind when you decide how many locale values your app stores.
BCP 47 language tags
Browsers and the Intl APIs identify locales with BCP 47 language tags. A tag is a sequence of subtags separated by hyphens. Each subtag has a fixed position and a conventional letter case.
| Subtag | Meaning | Example | Case |
|---|---|---|---|
| Language | ISO 639 language code, required | `de`, `fil` | lowercase |
| Script | ISO 15924 writing system, optional | `Hant`, `Latn` | Title case |
| Region | ISO 3166 country or UN M.49 area, optional | `AT`, `419` | UPPERCASE |
| Variant | Dialect or orthography, optional | `1996` | lowercase |
| Extension | Extra preferences, optional | `-u-nu-arab` | lowercase |
Some real tags:
en: English, no region.en-GB: English as used in Great Britain.pt-BR: Brazilian Portuguese.zh-Hant-TW: Chinese in the Traditional script, as used in Taiwan.es-419: Spanish for Latin America, a region that is not a single country.ar-EG-u-nu-latn: Arabic for Egypt, but with Western digits.
Matching is case-insensitive by specification. Stick to the conventional casing anyway, because some libraries and file systems compare tags as plain strings.
Scripts matter
Sometimes a region cannot tell you what to render. Chinese is written in Simplified or Traditional characters, and Serbian is written in Cyrillic or Latin. For these languages, zh-CN and zh-TW are only an approximation. Hong Kong users can read Traditional text, so zh-Hant is a more honest name for the catalog than zh-TW. Use a script subtag when the script is the real difference between two translations.
Working with tags in code
The Intl.Locale object parses a tag and exposes its parts. Intl.getCanonicalLocales validates tags and normalises their casing.
const locale = new Intl.Locale('zh-Hant-TW');
console.log(locale.language); // 'zh'
console.log(locale.script); // 'Hant'
console.log(locale.region); // 'TW'
console.log(Intl.getCanonicalLocales('EN-us')); // ['en-US']
console.log(new Intl.Locale('en').maximize().toString()); // 'en-Latn-US'
console.log(new Intl.Locale('zh-Hans-CN').minimize().toString()); // 'zh'
try {
Intl.getCanonicalLocales('en_US');
} catch (error) {
console.log(error instanceof RangeError); // true
}maximize() fills in the most likely script and region. minimize() removes whatever can be inferred. The last example shows the most common mistake: an underscore is not valid BCP 47. Many platforms, including Java, Android resources and gettext, write en_US. If a value comes from such a source, replace _ with - before you pass it to Intl, which throws a RangeError on malformed tags.
Common mistakes in tags
- Region used as language.
jpis not Japanese (ja).gbis not a language.usis not English. - Region only. A tag cannot start with a region.
USalone is invalid as a locale. - Wrong order. The order is language, script, region.
TW-zhis invalid. - One code for a whole language. Brazilian and European Portuguese differ enough that some products ship both
pt-BRandpt-PT.
What the browser tells you
navigator.language is the user's preferred locale. navigator.languages is the full ordered preference list, for example ['de-AT', 'de', 'en-US', 'en']. A server sees the same preferences in the Accept-Language header. Both reflect browser settings, not the user's location.
You rarely support every locale a user requests, so you must pick the best match from the ones you have. This is locale negotiation. The following function tries each requested tag in order. For each tag it removes subtags from the right until something matches.
export function negotiate(
requested: readonly string[],
supported: readonly string[],
fallback: string,
): string {
for (const tag of requested) {
let canonical: string;
try {
canonical = Intl.getCanonicalLocales(tag)[0];
} catch {
continue; // skip malformed tags
}
const parts = canonical.split('-');
while (parts.length > 0) {
const attempt = parts.join('-').toLowerCase();
const match = supported.find((s) => s.toLowerCase() === attempt);
if (match) return match;
parts.pop();
}
}
return fallback;
}
// 'de-AT' is not supported, but 'de' is:
console.log(negotiate(['de-AT', 'en-US'], ['en', 'de'], 'en')); // 'de'
// Nothing matches, so the fallback wins:
console.log(negotiate(['ja-JP'], ['en', 'de'], 'en')); // 'en'This function has a limit. A request for pt will not match a catalog that exists only as pt-BR, because trimming only removes subtags and never adds them. If you ship only regional catalogs, list the plain-language tag as an alias or add maximize() logic.
Fallback strategy
A fallback chain is the ordered list of locales the app tries when a message is missing. A good chain moves from specific to general, then to a language you always translate completely:
- The exact locale,
de-AT. - The base language,
de. - A deliberate sibling if one makes sense, such as
pt-BRforpt-PT. - The default language, usually
en.
With react-i18next, you describe the chain in the configuration. This example keeps one de catalog that serves all German regions, and uses pt-BR for European Portuguese until a pt-PT catalog exists:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n.use(initReactI18next).init({
resources: {
en: { translation: { hello: 'Hello' } },
de: { translation: { hello: 'Hallo' } },
'pt-BR': { translation: { hello: 'Olá' } },
},
lng: 'de-AT',
supportedLngs: ['en', 'de', 'pt-BR'],
nonExplicitSupportedLngs: true,
fallbackLng: {
'pt-PT': ['pt-BR'],
default: ['en'],
},
interpolation: { escapeValue: false },
});supportedLngs limits which locales the library will try to load. nonExplicitSupportedLngs: true lets de-AT count as supported because de is listed. Without it, i18next treats de-AT as unsupported and skips it. The object form of fallbackLng sets a chain per locale, with default as the catch-all. Chapter 4 covers the rest of the setup.
Choosing which locales to ship
Start with language-level catalogs (de, fr, es) and add regional catalogs only where wording really differs, such as en-GB for spelling or pt-PT for vocabulary. Formatting is a separate matter. Always pass the full tag, such as de-AT, to Intl formatters, even when the text catalog is plain de. This way, one German catalog still produces correctly formatted Austrian and Swiss numbers and dates.
Exercise
A user's browser sends navigator.languages as ['fr-CA', 'en-GB']. Your app has catalogs for 'en', 'fr' and 'de', with 'en' as the default. What does negotiate(navigator.languages, ['en', 'fr', 'de'], 'en') return, and why? What would it return if the supported list were only ['en-US', 'de']?
Show answer
It returns 'fr'. The tag 'fr-CA' is not supported, so the function removes the region and finds 'fr' before it looks at 'en-GB'. With ['en-US', 'de'] it returns 'en-US' as a fallback only by chance: 'fr-CA' and 'fr' do not match, and 'en-GB' trims to 'en', which does not match 'en-US' either, so nothing matches and the function returns the fallback argument. The result depends on what you pass as fallback. This shows that trimming never adds subtags.
Exercise
Which of these are valid BCP 47 tags, and what is wrong with the others? (a) en_GB (b) sr-Latn-RS (c) JP (d) zh-Hant
Show answer
(b) and (d) are valid. (a) uses an underscore instead of a hyphen. (c) is a region code, not a language: Japanese is 'ja', so the correct tag is 'ja' or 'ja-JP'.