Internationalization is the architectural foundation for shipping your app in multiple languages. It is not "add a JSON file and call it done" — it is a pipeline that touches every layer of the stack: build tooling, runtime loading, bundle splitting, layout rendering, accessibility, and SEO. A well-designed i18n system supports ICU message format, lazy-loaded locale bundles, RTL layout mirroring, and compile-time message extraction without forcing every developer to think about translations.
An internationalization system for a modern single-page application. The goal: every user-facing string is translated, dates and numbers are locale-aware, the layout flips automatically for RTL scripts (Arabic, Hebrew, Urdu), and the entire system adds less than 3 KB to the baseline bundle. The translation pipeline must integrate with the build step, support runtime locale switching without a page reload, and degrade gracefully when a translation key is missing.
We will design this system using the RADIO framework: Requirements, Architecture, Data Model, Interface API, and Optimization. Each section builds on the decisions of the previous one.
Key Insight
i18n is often confused with l10n (localization). i18n is theengineering — the framework, the pipeline, the APIs. l10n is the content — the translations themselves. This article covers i18n. Your translators own l10n.
1 · Requirements & Scoping (R)
Before writing a line of code, we need to define the boundaries of the system. The requirements fall into three layers: what the user sees, what the developer experiences, and what the build pipeline produces.
Functional requirements
String translation: Every user-facing string must be translatable. Translations are stored in locale bundles and resolved at runtime via a key-based lookup.
Variable interpolation: Strings may containdynamic values — "Welcome back, {name}!" — injected at rendertime without breaking the translation.
Pluralization: Each locale has unique plural rules. Arabic has 6 forms (zero, one, two, few, many, other). Polish has 3 (one, few, many). The system must use the correct form per count automatically.
Date & number formatting: Dates, currencies, percentages, and numbers must follow locale conventions: MM/DD/YYYY for US, DD/MM/YYYY for UK, YYYY-MM-DD for Sweden.
Rich-text translation: Strings may contain inline markup — "By clicking you agree to the {terms}." — where the HTML is provided by the component and only the surrounding text comes from the translation.
RTL layout support: Arabic, Hebrew, Farsi, and Urdu read right-to-left. The entire layout must mirror without manual overrides per component. CSS logical properties are the mechanism.
Runtime locale switching: The user changes language in a settings panel. The UI updates immediately. No page reload. No full app remount.
Non-functional requirements
Bundle size: The i18n runtime must add under 3 KB gzipped. Locale-specific data (translations, plural rules, CLDR data) must be code-split per locale.
SEO: The server must render <html lang="..." dir="..."> correctly. Hreflang tags, localized sitemaps, and canonical URLs must be generated at build time.
Fallback chain: If a key is missing in the current locale, the system falls back to the default locale (typically en-US). If still missing, the key itself is displayed as a last resort.
Developer experience: Type-safe translation keys. Compile-time extraction of strings to prevent missing translations in production. Lint rules that fail CI when a key is used without a corresponding translation.
Performance: Translation lookup must be O(1). Locale switching must not cause layout thrashing. Initial load must deliver only the current locale's bundle.
I deliberately scoped out machine translation. It is a product feature, not an infrastructure concern. The i18n system should make it easy for human translators to do their job. If you want auto-translation later, it plugs into the translation management platform, not into the frontend runtime.
2 · Architecture & High-Level Design (A)
The i18n architecture is a pipeline from source code to rendered pixels. At design time, developers write ICU messages directly in the source. At build time, a CLI tool extracts those messages into a portable format (XLIFF or JSON), translators fill in the target languages, and the build step compiles them into optimized locale bundles. At runtime, the app loads only the current locale's bundle and resolves messages through a context provider.
Figure 1 — i18n system architecture. Source messages are extracted during build, compiled to efficient JS functions, and loaded at runtime via a React context provider with supporting subsystems.
I evaluated three architectural patterns before settling on a provider-based design with compile-time extraction.
Option A: Global singleton (rejected)
A global i18n object initialized once at app boot. Simple to understand, but impossible to test (shared mutable state leaks between test cases), useless for SSR (the singleton is shared across requests in Node.js), and prevents code-splitting (every locale loads at boot).
Option B: Per-component HOC (rejected)
Each component receives translations as props via a higher-order component or a React context. Flexible, but every component that needs translations must be wrapped, the HOC tree grows deep, and you cannot share formatting utilities (date/number/plural) across components without passing them down manually.
Option C: Context provider + hook (chosen)
A single I18nProvider wraps the app tree. Components access translations via a useTranslations hook. The provider holds the locale state, the message bundle, and the formatting utilities. This is the pattern used by react-intl, next-intl, and Lingui — it is testable, SSR-safe, and supports code-splitting naturally because the message bundle is passed as a prop.
Global singleton
Simple but not SSR-safe, not testable, no code-splitting. Rejected.
Per-component HOC
Flexible but verbose, deep wrapper tree, no shared formatters. Rejected.
The provider pattern also solves the SSR problem cleanly. On the server, each request creates a new provider instance with the requested locale. On the client, the provider reads the locale from the initial HTML payload and hydrates without a flash of untranslated content.
3 · Data Model & Message Format (D)
The data model for i18n is deceptively simple: a map of keys to translated strings. But the format of those strings — ICU MessageFormat — introduces its own mini-language for plurals, selects, numbers, and dates. Getting the format right determines whether translators can work independently and whether the system can scale to 40+ locales.
Translation file structure
I chose a flat key structure — no nesting. Nested JSON objects look cleaner in the file but create ambiguity: is the key "app" or app.title? Flat keys are unambiguous and simpler to query in O(1):
Each locale is a single JSON file. The file is loaded on demand and parsed once. The flat structure means lookup is a simple bracket access: messages["welcome"].
ICU MessageFormat — the standard
ICU MessageFormat is the industry standard for translation strings. Developed by the Unicode Consortium, it is used by Mozilla, Apple, Google, and every major translation management platform. The format supports:
Variable interpolation:{name} inserts a dynamic value.
Plural selection:{count, plural, one {...} other {...}} selects the correct plural form.
Select ordinals:{count, selectordinal, one {...} two {...}} for "1st, 2nd, 3rd."
Date/number formatting:{date, date, medium} formats a date according to locale conventions.
Select:{gender, select, male {...} female {...} other {...}} for gender-aware messages.
Plural rules per locale
Different languages have different plural categories. English has two (singular "one", plural "other"). Polish has three (one, few, many). Arabic has six (zero, one, two, few, many, other). The system uses Intl.PluralRules — a built-in browser API — to determine which plural category a count belongs to for the current locale:
example.typescript
const plurals = {
"en-US": {
"cart.items":
"{count, plural, one {# item} other {# items}}",
},
"pl-PL": {
"cart.items":
"{count, plural, one {# przedmiot} few {# przedmioty} many {# przedmiotów} other {# przedmiotu}}",
},
"ar-SA": {
"cart.items":
"{count, plural, zero {# عنصر} one {# عنصر} two {# عنصران} few {# عناصر} many {# عنصراً} other {# عنصر}}",
},
};
function pluralExample(locale: string, count: number) {
const pr = new Intl.PluralRules(locale);
const rule = pr.select(count);
return `For ${locale}, count=${count} → ${rule}`;
}
The ICU parser reads the plural forms from the message string and selects the correct one based on the Intl.PluralRules output. This means translators write all plural forms in one string, and the runtime picks the right one automatically.
Note
I considered using Intl.MessageFormat (native browser API) but it is not yet widely supported. The polyfill from @formatjs/intl is the de facto standard — used by react-intl, Lingui, and Next.js's built-in i18n. It adds ~6 KB gzipped, which is acceptable for the i18n runtime.
Compile-time vs runtime parsing
ICU messages can be parsed at runtime (load the JSON, parse each string when rendered) or at compile time (parse during the build and emit ASTs instead of raw strings). I chose a hybrid: the development build keeps raw strings for hot-reload and debugging; the production build precompiles messages to ASTs, which eliminates parsing at runtime and reduces the bundle by ~40%.
4 · Interface Definition — API (I)
The API surface of an i18n system has three layers: the provider that wraps the app, the hook that components use, and the compile-time CLI that extracts messages. Each layer has a narrow contract.
The provider receives the locale and messages as props. This is deliberate: the provider does not fetch data or read cookies. It is a pure render-prop container. The locale resolution logic lives upstream, in a LocaleDetector that reads from the URL, cookie, or Accept-Language header.
Hook API — useTranslations
The hook returns a t() function for plain-text translation and a rich() function for messages with embedded React components. Both accept ICU-style interpolation values:
The separation between t() and rich() is intentional. Plain-text messages can be optimized as simple string lookups. Rich messages require React element reconciliation and are slower. By splitting the API, the developer consciously chooses which variant they need.
Locale resolution chain
The system resolves the locale in this order:
1. URL path:/ar-SA/settings overrides everything. This is the primary mechanism for SEO — each locale has a canonical URL.
2. Cookie: If the user previously selected a language, the NEXT_LOCALE cookie stores it.
3. Accept-Language header: The browser's preferred language, parsed by negotiateLanguages() from the @formatjs/intl package.
4. Default locale: Hard-coded fallback to en-US.
Compile-time extraction API
The CLI tool scans source files for calls to t() and rich(), extracts the key and the default message, and generates a skeleton locale file. The command looks like:
example.text
# Extract messages from source
$ i18n extract --src="./app" --locales="./locales"
# Compile ICU messages to AST for production
$ i18n compile --locales="./locales" --out="./public/locales"
# Validate: fail CI if keys are missing
$ i18n validate --locales="./locales" --strict
The extraction step uses a custom Babel plugin that walks the AST looking for CallExpression nodes matching the t() or rich() pattern. It captures both the key (first argument) and the default message (second argument, if present). This ensures no string is missed, even if it is conditionally rendered.
5 · Component Deep Dive
Three subsystems deserve a closer look: locale bundle loading, the ICU message resolver, and the RTL layout engine.
Lazy locale bundle loading
Locale bundles are loaded on demand using dynamic import(). When the user switches from English to Arabic, the app fetches /locales/ar-SA.json without a page reload. The provider shows a skeleton placeholder while the bundle loads and swaps it in atomically:
The import() call is the key. Modern bundlers (webpack, Rspack, Vite) treat dynamic imports as split points. Each locale file becomes a separate chunk. The browser only downloads the current locale on first visit.
ICU message resolver
When t("inbox.count", { count: 3 }) is called, the resolver:
Looks up the key in the current locale's message bundle (O(1) bracket access on a flat object).
If the key is missing, walks the fallback chain: current locale → parent locale (e.g. ar if ar-SA is missing) → default locale (en-US) → raw key string.
Parses the ICU message into an AST (or reads a precompiled AST in production).
Evaluates the AST: resolves plural/select arguments against Intl.PluralRules, formats dates and numbers with Intl.DateTimeFormat and Intl.NumberFormat, interpolates simple values.
Returns the formatted string.
In production, step 3 is skipped entirely — the AST is precompiled. This cuts message resolution time by ~60%.
RTL layout engine
RTL support is the most commonly neglected i18n concern. Many apps slap dir="rtl" on the <html> tag and call it done. But real RTL support requires:
CSS logical properties: Use margin-inline-start instead of margin-left. Use border-inline-end instead of border-right.
Mirrored icons: Chevrons, arrows, and triangle indicators must flip in RTL. Use CSS scale: rtl(-1, 1) or the dir attribute in SVG.
Text alignment: Default text-align for paragraphs, headings, and labels must inherit from the dir attribute, not be hard-coded to left.
Form layout: Labels before inputs become labels after inputs. The flex direction on form rows must use row (which auto-flips) rather than row-reverse.
CSS-in-JS libraries that use runtime-style injection (styled-components, emotion) often do not support logical properties out of the box. If you use CSS-in-JS, verify that your library resolves margin-inline-start correctly in all browsers. Tailwind CSS v4 supports logical properties via the ms- and me- prefixes.
Figure 3 — RTL layout mirroring. CSS logical properties eliminate the need for direction-specific styles. The dir attribute on <html> flips all layouts automatically.
6 · Data Flow & Locale Resolution
Let's trace a complete lifecycle: a user visits the app for the first time with their browser set to Arabic (Saudi Arabia).
Figure 4 — Translation resolution flow. The resolver walks a fallback chain (region → language → default → key ID), then processes the ICU message with variables and plural rules to produce the final rendered string.
1. HTTP request arrives
The server reads the Accept-Language header: ar-SA,ar;q=0.9. The middleware negotiates the best match against supported locales.
The server loads the ar-SA message bundle, creates an I18nProvider, renders the page. HTML includes lang="ar-SA" dir="rtl".
4. Hydration — client loads same bundle
The client JSON-serializes the locale and messages into the HTML. Hydration reads them from a script tag — no network request.
5. User switches to French
LocaleSwitcher fires. Dynamic import fetches /locales/fr-FR.json. Provider swaps messages atomically. document.dir updates to "ltr". No page reload.
The key optimization is step 4: serializing the locale and messages into a <script> tag in the HTML. This eliminates the network waterfall on first load — the client already has the translations before React hydrates. Without this, the client would render untranslated content, then fetch the locale bundle, causing a flash-of-untranslated-content (FOUC).
Key Insight
The serialization trick is the same pattern used by TanStack Query and SWR for cache hydration. You render on the server, serialize the result into the HTML, and the client reads it synchronously on the first render. The data is ready before the JavaScript bundle finishes executing.
7 · Performance Optimization (O)
i18n has a direct impact on perceived performance. Every translation lookup is a function call in the render path, and every locale bundle is a network request. Here are the optimizations I consider essential for a production-grade system.
Per-locale code splitting
Each locale file becomes a separate webpack chunk via dynamic import(). The initial HTML payload contains only the detected locale's bundle, serialized inline. Unused locales are never downloaded:
Figure 2 — Locale bundle code-splitting. Only the active locale's messages and Intl data are loaded. Dynamic imports keep the main bundle locale-free.
Compile-time AST precompilation
ICU parsing is the most expensive part of message resolution. In development, we parse at runtime to support hot-reload. In production, we precompile messages to ASTs during the build step. This eliminates the parse step entirely:
Raw JSON (dev): ~8 KB per locale, parsed at runtime. ~1ms per message on first access.
Precompiled AST (prod): ~5 KB per locale, zero parsing. ~0.3ms per message.
Memoized translation functions
The t() function returned by useTranslations is memoized per render cycle via useCallback. Components that receive t as a prop only re-render when the locale changes, not on every parent re-render.
CLDR data trimming
The Unicode CLDR database is massive — hundreds of KB per locale. The @formatjs/intl packages use "locale data trimming": they only include the CLDR data that your messages actually reference. If you never use date, full, the full date format data is excluded from the bundle.
Tradeoff table
Strategy
Pros
Cons
Runtime JSON parsing
Simple, hot-reload friendly
~1ms per message parse, larger bundle
Precompiled AST (chosen)
~0.3ms per message, 40% smaller locale files
Build step required, harder to debug
All locales in one bundle
Zero network requests for locale switching
Huge initial bundle, wasteful for 40+ locales
Per-locale splitting (chosen)
Only current locale loaded, scales to N locales
Latency on first switch after hydration
CSS logical properties
Automatic RTL, no JS runtime, no extra CSS file
Requires browser support audit
Bundle size budget
The full i18n runtime, including ICU parser, locale negotiation, and the React context provider, adds approximately 8 KB gzipped to the baseline bundle. Each locale bundle (precompiled AST) adds 2-8 KB depending on message count. For an app with 200 messages in 10 locales, the total i18n cost is ~8 KB (runtime) + one locale (avg 5 KB) = 13 KB gzipped on initial load.
8 · Security Considerations
i18n has a surprisingly large security surface because translation bundles are external data that is parsed and rendered as HTML.
XSS via translation strings: If a translation bundle is compromised, an attacker can inject arbitrary HTML. Since we use rich() for rich messages and t() returns plain text, the risk is contained: t() escapes all HTML by design. For rich(), unknown tags in the ICU string are dropped during compilation.
Locale bundle integrity: Locale bundles are static JSON files served from the CDN. Use Subresource Integrity (SRI) hashes to ensure they have not been tampered with.
Accept-Language fingerprinting: The Accept-Language header leaks the user's language preferences, which can be used for fingerprinting. Do not log or transmit the raw header value to analytics without consent.
SSR locale injection: If the locale is read from a URL parameter (e.g., /?locale=ar-SA), ensure it matches a known locale before using it. Unvalidated locale values can lead to path traversal attacks when loading locale files.
Warning
Always sanitize the locale value before using it in a file path or URL. Use an allowlist of supported locales. Never do import(`./locales/${userInput}.json`) without validating userInput against a known list.
9 · Testing Strategy
i18n testing has three layers: unit tests for the message resolver, component tests with locale context, and integration tests for locale switching.
Unit: message resolver
The ICU resolver is a pure function: messages in, string out. Test each ICU feature — interpolation, plurals, selects, dates — in isolation.
Component: render with locale context
Each component that uses translations should be tested by wrapping it in a test provider with a minimal message bundle:
Interpolation: Verify that {name} is replaced correctly. Test with empty string, special characters, and numbers.
Plural rules: Test each plural category for the locale. For Arabic, test zero, one, two, few, many, other.
Fallback chain: Remove a key from the current locale. Verify it falls back to parent locale, then to default, then to raw key.
Locale switching: Render with locale A, switch to locale B, verify the text updates.
RTL attribute: Render with an RTL locale, verify dir="rtl" on the document element.
Missing key: Call t() with a nonexistent key. Verify it returns the key itself.
Integration: extract → translate → validate
The CI pipeline should run i18n validate --strict to catch missing translations before deployment. The command fails if any key in the source is missing from a locale bundle, or if a locale bundle contains an unused key.
Note
Stale keys are a real problem in long-lived projects. As the codebase evolves, developers remove or rename translation keys. The validate step should warn on unused keys and offer an --prune flag to remove them automatically.
10 · Accessibility & RTL
Internationalization and accessibility intersect in three critical areas: language declaration, RTL layout, and locale-aware ARIA attributes.
Language declaration
The <html lang="..."> attribute is the most important a11y property for i18n. Screen readers use it to select the correct voice synthesizer and pronunciation rules. If the attribute is wrong — e.g., lang="en" on an Arabic page — the screen reader will attempt to read Arabic text with an English voice, resulting in unintelligible output.
The dir attribute controls text direction. It must be "ltr" for most languages and "rtl" for Arabic, Hebrew, Farsi, and Urdu. Do not use CSS direction: rtl — it does not automatically update the dir attribute, which breaks screen reader behavior.
example.html
<!-- ✅ Correct: lang + dir on <html> -->
<html lang="ar-SA" dir="rtl">
<body>
<p>مرحبا بالعالم</p>
</body>
</html>
<!-- ❌ Wrong: CSS direction without dir attribute -->
<html lang="ar-SA">
<body style="direction: rtl">
<!-- Screen reader still uses LTR voice -->
<p>مرحبا بالعالم</p>
</body>
</html>
Locale-aware ARIA
ARIA attributes are language-agnostic, but their values should be translated. For example, aria-label="Close dialog" becomes aria-label="إغلاق الحوار" in Arabic. Always pass ARIA label values through the t() function, just like visible text.
Font and typography considerations
Different scripts require different font families. Arabic and Urdu use Noto Naskh Arabic. Japanese uses Noto Sans JP. Chinese uses Noto Sans SC. The font loading strategy should account for this: load a fallback font stack that covers all supported scripts, then swap to locale-optimized fonts when they load. The font-display: swap CSS property prevents invisible text while the font loads.
Line height also varies by script. Arabic text is typically taller than English text at the same font size. Use relative line heights (line-height: 1.6) instead of absolute values to accommodate script differences automatically.
Key Insight
The dir attribute is inherited by all descendants, but it does not automatically mirror scrollbars, input cursors, or the order of table columns. Test every RTL locale against your full component library. A component that works perfectly in English can break in Arabic — especially third-party widgets (date pickers, rich text editors) that do not respect the inherited direction.
11 · Key Takeaways
i18n is an architecture decision, not a library choice. The translation pipeline touches the build step, the server renderer, the client runtime, the CSS system, and the testing infrastructure. Choose a provider + hook pattern with compile-time extraction.
ICU MessageFormat is the standard. It supports plurals, selects, dates, numbers, and rich-text in a single string format understood by every translation management platform.
Precompile ICU to ASTs in production. Runtime parsing adds ~1ms per message. Precompilation eliminates the parse step entirely and reduces locale bundle size by ~40%.
Per-locale code splitting is mandatory. A single bundle with all locales will exceed the 3 MB Worker limit for apps with more than 10 locales. Dynamic import() creates separate chunks automatically.
RTL is not just dir="rtl". CSS logical properties, mirrored icons, flex direction awareness, and scrollbar handling all require systematic attention. Use margin-inline-start everywhere, never margin-left.
Serialize locale data into the HTML payload. This eliminates the flash-of-untranslated-content on first load.
Validate translations in CI. Missing keys, stale keys, and ICU syntax errors should fail the build. Run i18n validate --strict before every deployment.
i18n is invisible when done right. The user just sees their language, their date format, their layout direction. The complexity — the ICU parser, the lazy loading, the CSS logical properties, the fallback chain — stays beneath the surface. That is the mark of a well-designed system: it does not ask the user to care about infrastructure.