i18next Setup — i18n

i18next 27 keeps dictionaries per language and namespace (JSON v4 with {{slot}} and the _one/_other suffixes); react-i18next 18 gives…

A guest from Japan opens Mrs. Sri's page, but the free cancellation sentence hasn't been translated into Japanese yet. What shows up? The Mist Homestay front desk already has a way. On the shelf there is one binder per language, and every sentence has a page label. The Japanese guest asks for the "cancel" page, so the receptionist opens the Japanese binder. If the page is empty, she takes the next binder on the backup list. If no binder has it, she just reads out the page's label. i18next, the most widely used JavaScript i18n library, works exactly like that. It keeps a dictionary per language and gives you a t() function that fetches text from it, and t('cancel') searches in that same order. react-i18next is its bridge to React.

Install and init

Used in this lesson (as of November 2026): i18next 27.1.1 and react-i18next 18.0.1 (needs i18next 27.0.1 or newer, React 18 or newer, and Node.js 22 or newer). React 16 or 17 apps stay on react-i18next 17.0.16 with i18next 26.4.3. The version 27 changes are in the i18next migration guide. Install with npm install i18next react-i18next.

// src/i18n.js: runs once, before the app renders
import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';
import enUS from './locales/en-US/booking.json';
import enGB from './locales/en-GB/booking.json';
import jaJP from './locales/ja-JP/booking.json';
import arEG from './locales/ar-EG/booking.json';

i18next.use(initReactI18next).init({
  lng: 'ja-JP',                      // the language in use now
  fallbackLng: ['en-GB', 'en-US'],   // backups, tried in order
  ns: ['booking'],                   // namespace = one dictionary file per feature
  defaultNS: 'booking',              // namespace for t('room') with no prefix
  resources: { 'en-US': { booking: enUS }, 'en-GB': { booking: enGB }, 'ja-JP': { booking: jaJP }, 'ar-EG': { booking: arEG } },
  interpolation: { escapeValue: false }, // React already escapes text
});

Dictionary files and t()

i18next dictionaries use the JSON v4 format. This is Mrs. Sri's source dictionary, locales/en-US/booking.json:

{
  "room": "Terrace Room",
  "nights_one": "{{count}} night",
  "nights_other": "{{count}} nights",
  "total_one": "Total for {{count}} night: {{price}}",
  "total_other": "Total for {{count}} nights: {{price}}",
  "book": "Book now, pay at the homestay",
  "cancel": "Free cancellation up to {{days}} days before check-in.",
  "breakfast": "Breakfast included",
  "thanks": "Thank you, {{name}}!"
}

{{price}} is an interpolation slot, filled from the second argument of t(). The _one and _other suffixes are plural forms; ja-JP only needs nights_other. The ja-JP dictionary is not complete yet: it has no book, cancel or breakfast. Mrs. Sri also keeps en-GB, a British English copy of the source, and it has no breakfast, a new key from Mrs. Sri.

import { useTranslation } from 'react-i18next';

function BookingCard({ nights, price }) {
  const { t, i18n } = useTranslation('booking');
  return (
    <article>
      <h2>{t('room')}</h2>
      <p>{t('total', { count: nights, price })}</p>
      <button>{t('book')}</button>
      <button onClick={() => i18n.changeLanguage('ar-EG')}>العربية</button>
    </article>
  );
}
// ja-JP, nights = 2: "テラスルーム", "2泊の合計:$70", "Book now, pay at the homestay"

The fallback chain: ja-JP, ja, en-GB, en-US

For lng: 'ja-JP', i18next reads languages in order: ['ja-JP', 'ja', 'en-GB', 'en-US']. ja (the language without its region) is added on its own; the rest come from fallbackLng. The results from i18next 27.1.1, the same as from 26.4.3:

t(...) in ja-JP ja-JP ja en-GB en-US Result
t('room') there テラスルーム
t('cancel', { days: 3 }) missing missing there Free cancellation up to 3 days before check-in.
t('breakfast') missing missing missing there Breakfast included
t('deposit') missing missing missing missing deposit

The order is a business decision: Mrs. Sri wants guests from abroad to read her British English copy first, so en-GB comes before en-US, the source, which has every key. fallbackLng can also be an object: { 'ja-JP': ['en-GB', 'en-US'], default: ['en-US'] }.

Plurals: the _one, _other suffixes and friends

i18next picks the suffix with Intl.PluralRules. For each language in the chain it tries key_<category> and then the plain key; when count is 0, key_zero is tried first, in English too. Our ar-EG dictionary only has nights_one, nights_two and nights_other:

t('nights', { count }) in ar-EG Category Found Result
1 one ar-EG nights_one ليلة واحدة
2 two ar-EG nights_two ليلتان
3 few ar-EG nights_other 3 ليلة (grammatically wrong)
100 other ar-EG nights_other 100 ليلة

There is no nights_few. Since i18next 27.1, i18next then uses nights_other from the same language, so the result is "3 ليلة", while Arabic needs the form ليالٍ for 3 nights. i18next 26 instead moves on to en-GB, calculates the category with English rules (3 is other), and writes "3 nights". Both are wrong, so every language needs all of its own categories. {{count}} is written as it is ("3", not "٣"); {{count, number}} formats it for the language.

A team that already has ICU dictionaries from the react-intl lesson can use the i18next-icu plugin 2.5.0 (needs intl-messageformat 10.3.3 up to below 13): i18next.use(ICU), and then t('nights', { n: 3 }) in ar-EG gives ٣ ليالٍ.

When a key isn't found

When a key is in none of the languages in the chain, t() returns the key itself. Without fallbackLng, the ja-JP chain is only ['ja-JP', 'ja'] (version 26: ['ja-JP', 'ja', 'dev']), so t('cancel') shows the word cancel, not the English text and not an empty string.

i18next.init({
  // ...the options above, plus:
  saveMissing: true,
  missingKeyHandler: (lngs, ns, key, fallbackValue) => console.warn('Missing key:', lngs, ns, key),
});
t('deposit');                                   // "deposit", handler: ["en-GB","en-US"] "booking" "deposit"
t('deposit', { defaultValue: 'No deposit' });   // "No deposit"

escapeValue: why React turns it off

The default is interpolation.escapeValue: true: values that go into slots are escaped for HTML (& becomes &amp;, < becomes &lt;, and so do >, " and '; i18next 26 also escapes /). The booking is under "Rina & Hadi", so in ja-JP the result is Rina &amp; Hadi様、ありがとうございます。. React renders that text as it is, and the guest sees the letters &amp;. React already escapes all text in JSX, so React setups use escapeValue: false. If the result of t() goes into innerHTML or dangerouslySetInnerHTML, nothing escapes it again: there, keep true.

Language detection and backends

import LanguageDetector from 'i18next-browser-languagedetector';
import HttpBackend from 'i18next-http-backend';

i18next.use(HttpBackend).use(LanguageDetector).use(initReactI18next).init({
  fallbackLng: ['en-GB', 'en-US'],
  backend: { loadPath: '/locales/{{lng}}/{{ns}}.json' },
  detection: { order: ['querystring', 'localStorage', 'navigator'], caches: ['localStorage'] },
  interpolation: { escapeValue: false },
});

This Lab: a small, honest i18next subset

i18next isn't installed in BelajarWeb.dev, and the Playground can't install npm packages. So the Lab uses a home-made t() (about 50 lines): ns:key, {{name}} with escapeValue, the _zero and _<category> suffixes, the fallbackLng chain, returnEmptyString, defaultValue and saveMissing. Not supported: $t() nesting, {{x, number}}, context, ordinals, plugins and backends. Compared with i18next 26.4.3 on the dictionaries above, eight lng values, five forms of fallbackLng, eight count values and every combination of escapeValue and returnEmptyString: 79,680 of 79,680 results identical, missingKeyHandler calls included. So this Lab follows i18next 26. i18next 27 differs in four places: no 'dev' without fallbackLng, returnEmptyString is false by default, / is not escaped, and a missing plural category uses the same language's _other.

⚠️ i18next setups that are quietly wrong

TL;DR: i18next 27 keeps dictionaries per language and namespace (JSON v4 with {{slot}} and the _one/_other suffixes); react-i18next 18 gives useTranslation('booking') and t(). init needs lng (or a detector), fallbackLng, ns, defaultNS, and interpolation.escapeValue: false because React already escapes. fallbackLng is the backup language used when a translation for the active language isn't found: ja-JP is read as ja-JP, ja, en-GB, en-US. Without it (the default is false since version 27, 'dev' in version 26), a missing key shows as the raw key; saveMissing with missingKeyHandler reports it. Plural forms are picked by Intl.PluralRules per language, and a category missing from that language's file uses the same language's _other since i18next 27.1 (version 26: jumps to the next language), so write every category. The language detection plugin is i18next-browser-languagedetector (querystring, cookie, localStorage, sessionStorage, navigator, htmlTag), dictionaries over HTTP come with i18next-http-backend, ICU syntax with i18next-icu.

⚡ init once, before the app renders

Write:

i18next.use(initReactI18next).init({
  lng: 'ja-JP',                      // the language in use now
  fallbackLng: ['en-GB', 'en-US'],   // backups, tried in order
  defaultNS: 'booking',              // namespace for t('room') with no prefix
});

Meaning: lng is the active language. fallbackLng is the backup language, used when a translation for the active language isn't found.

⚡ The fallback chain

Guess first: the ja-JP dictionary has no cancel yet. What does t('cancel', { days: 3 }) show?

The en-GB text: "Free cancellation up to 3 days before check-in." i18next reads ja-JP, ja, en-GB, then en-US, and stops at the first language that has the key.

Meaning: Without fallbackLng (the default is false since i18next 27, 'dev' in version 26), t('cancel') shows the word cancel, the key itself.

⚡ t() in a component

Write:

const { t, i18n } = useTranslation('booking');
<p>{t('total', { count: nights, price })}</p>

Meaning: count picks the plural form (_one, _other) and also fills {{count}}. i18n.changeLanguage('ar-EG') switches the language, and every component with useTranslation re-renders.

What you will learn