What you'll learn: By the end of this lesson you will be able to separate internationalization from localization, choose a locale from an
Accept-Languageheader and a saved user choice, declare language and direction withlanganddir, write CSS that works left to right and right to left with logical properties, isolate text of unknown direction, and keep user-facing text in catalogs that fall back safely and show what is missing.
Think of a concert hall that is built once and then hosts many performances. The stage, the seats and the exits are designed so that any show can use them, and each show brings its own programme, costumes and language. If the hall had a left-handed door welded shut because the first show only needed a right-handed one, every later show would suffer.
A front end is that hall. Internationalization (often written i18n) is building it so that any language, script and reading direction can be added without rebuilding the walls. Localization (l10n) is bringing one particular show: the translated text, the local conventions and the review by people who know the language. This lesson is about the hall. The next one, Message Formatting, Plurals and the Intl APIs, is about how a single sentence is assembled for each audience.
The running example is a storefront that launches in English, German, Canadian French and Arabic. Its catalogs come from a small lab and are made up for the lesson.
The core idea
- A locale is a request, not a fact. The browser sends preferences, the user may have saved a choice, and the site supports a short list. Your code must turn those three into one answer and say how it got there.
- Language and direction are two settings.
langsays what language the text is in.dirsays which way lines run. Declare both on the root element, and never guess one from the other. - Write layout in terms of text flow, not screen sides. If the CSS says "start" and "end" instead of "left" and "right", the same stylesheet serves a right-to-left page.
Three illustrations run through the lesson: a minimal example (a page that declares lang and dir), a realistic example (the storefront choosing a locale and flipping its layout) and a failure example (a French customer from France who is served English).
Terms that people mix up
Internationalization is engineering work done once: no text in logic, no assumptions about direction, numbers or dates. Localization is content work done for every locale: translated text, formats, images and review. A locale is selected by a language tag such as de, de-AT or ar-EG.
RFC 5646 describes a tag as subtags separated by hyphens: the language first, then a script if present, then a region. Tags are case-insensitive, and the registry's convention is lowercase for languages, title case for scripts and uppercase for two-letter regions, as in sr-Latn-RS. A tag can carry a script (ar-Latn is Arabic written in Latin letters), and a tag such as ar with no script has a likely script that a program can fill in.
Choosing a locale
A request has up to three inputs, and they are not equal.
The browser sends an Accept-Language header. MDN describes it as indicating the natural language and locale that the client prefers. It carries a list of tags, each optionally followed by a quality value (q) that defaults to 1, and a wildcard * for "anything else":
Accept-Language: fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5
MDN calls the header a hint for when the server cannot determine the language otherwise, and says the server should never override an explicit user language choice. For privacy, the header may not contain the full list of preferences: in Safari, and in Chrome's incognito mode, only one language is listed.
The second input is the saved choice: the user picked German in the footer last week. That beats everything else. The third is the site's supported list.
Figure 1. Three inputs become one locale, and the decision is written into the page
How to read this: the negotiation step is a pure function with no network or storage of its own, which makes it easy to test. Its single output, the locale, selects the text and the markup attributes together, so they cannot disagree.
Matching a tag to what you support
Suppose a visitor asks for de-AT and you support de. RFC 4647 defines a lookup scheme for this: the language range is truncated from the end until a supported tag matches, and a single-letter subtag is removed together with the subtag after it. If nothing matches, a default is used, and the whole priority list must be tried before the default is chosen. JavaScript's Intl constructors follow the same idea: a list of locales is a prioritized request, a well-formed but unknown identifier is skipped, and the runtime's default locale is the last resort. The localeMatcher option chooses between "lookup" and a runtime-defined "best fit".
Lookup is conservative. It does not treat fr-FR as fr-CA: dropping -FR leaves fr, and if you support only fr-CA, nothing matches. Accepting a sibling region is a product decision, and the lab makes it an explicit option.
Figure 2. The order of precedence, as a decision
How to read this: each range is tried in order of quality. The default is reached only after every range has failed, never after the first.
Minimal example: declare language and direction
Every page names its language and its direction on the root element:
<html lang="ar" dir="rtl">
<body>
<p lang="en" dir="ltr">This paragraph is in English.</p>
</body>
</html>
MDN's lang page says the attribute holds a single BCP 47 tag, that a missing value leaves the language unknown, and that its main use is accessibility: WCAG 3.1.1 requires the page language to be programmatically determinable so that screen readers can pronounce text correctly. The dir page says the attribute sets the element's base text direction, takes ltr, rtl or auto, and recommends setting it on the root element, because lang "declares the language, but does not imply the base direction". W3C and MDN both advise keeping direction in markup rather than CSS, so it survives when styles do not load.
Where direction comes from
Direction belongs to the script, not to the language code. The lab derives it from the script of a tag, through Intl.Locale, and compares it with the runtime's own getTextInfo(), which MDN describes as returning a direction determined from the locale's script. MDN marks it as newly available in 2026, so code should not assume it exists in older browsers.
Build it: negotiate, set direction, find physical CSS
Goal. Run the negotiation, direction, CSS-finder and catalog functions through six scenarios and check each against the rules above.
Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic: no DOM, no browser.
cd examples/frontend
pnpm install
cd labs/locale-negotiation-rtl
pnpm test # 22 tests
node src/demo.ts
Steps.
- Run the tests, then the demo, and compare it with the output below.
- In scenario 2, compare the two
fr-FRlines: the strict version falls to the default, the opt-in version findsfr-CA. - In scenario 3, find the row where the language is Arabic and the direction is not right to left.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01; scenarios 2 and 3):
=== 2. negotiate against supported = [en, de, fr-CA, ar], fallback en
de-AT user -> de source=accept-language range=de-AT via=lookup
fr-FR user, strict -> en source=default
fr-FR user, same-language fallback -> fr-CA source=accept-language range=fr-FR via=same-language
first range unsupported -> en source=accept-language range=en via=exact
ar-EG user -> ar source=accept-language range=ar-EG via=lookup
no header -> en source=default
stored choice beats the header -> de source=explicit range=de via=exact
stored choice not supported -> ar source=accept-language range=ar via=exact
=== 3. direction comes from the script, not the language code
tag script own rule Intl getTextInfo html attributes
ar Arab rtl rtl lang="ar" dir="rtl"
he Hebr rtl rtl lang="he" dir="rtl"
fa Arab rtl rtl lang="fa" dir="rtl"
ur Arab rtl rtl lang="ur" dir="rtl"
en Latn ltr ltr lang="en" dir="ltr"
ja Jpan ltr ltr lang="ja" dir="ltr"
ar-Latn Latn ltr ltr lang="ar-Latn" dir="ltr"
pa-Arab Arab rtl rtl lang="pa-Arab" dir="rtl"
untrusted name: <bdi>Maria <b>O'Neil</b></bdi>
The ar-Latn row is the point: lang="ar-Latn" is Arabic, and its direction is left to right because it is written in Latin letters. A rule of "Arabic means right to left" gets it wrong.
What the lab does not show. No layout, no bidirectional reordering and no browser. Its list of right-to-left scripts has six entries, enough for the demo. Real products should ask the runtime where getTextInfo() exists, and keep a list for older browsers.
Making layout direction-proof
A physical CSS property names a screen side: margin-left is always the left. MDN describes logical properties as direction-relative equivalents, defined in terms of two abstract axes: the inline axis runs along a line of text and the block axis runs across lines, and what they mean physically depends on the writing mode. For margin-inline-start, MDN says it corresponds to the top, right, bottom or left margin depending on writing-mode, direction and text-orientation. In horizontal text on an ltr page, start is left; on an rtl page, start is right. The pattern is <property>-inline-start, -inline-end, -block-start and -block-end, and text-align accepts start and end.
.note { margin-inline-start: 2rem; } /* margin-left on ltr, margin-right on rtl */
.badge { position: absolute; inset-inline-end: 0; }
p { text-align: start; }
Scenario 4 of the demo scans a small stylesheet and reports five physical declarations (margin-left, padding-right, text-align: left, border-left and right) with their logical replacements. Scenario 5 resolves logical rules for both directions.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01; scenario 5):
=== 5. the same logical rule on a ltr page and on an rtl page
margin-inline-start ltr: margin-left rtl: margin-right
padding-inline-end ltr: padding-right rtl: padding-left
inset-inline-start ltr: left rtl: right
border-inline-end ltr: border-right rtl: border-left
text-align: start ltr: left rtl: right
text-align: left ltr: left rtl: left
The last line shows that an explicit text-align: left stays left on a right-to-left page. That is sometimes right (a code sample) and usually a bug. Logical properties fix spacing and alignment, not everything: a back arrow, a progress bar that fills from one side and a carousel each need a decision, and the lab does not model them. The CSS architecture lesson and the modern CSS layout lesson cover how to keep such rules in one place.
Text of unknown direction
A user's name, a review or a value from a database can be in any script. The dir page advises dir="auto" for data of unknown direction, and warns that it is a heuristic: it looks at the first strong character, so a comment that starts with an English name and continues in Arabic gets a left-to-right base direction. The bdi element isolates its content from the surrounding text and behaves as if dir="auto" were set; MDN's example is a name followed by "- 1st place", where a right-to-left name can pull the neutral characters of the label the wrong way. The lab's isolate function escapes the text first and then wraps it, because isolation is not a defence against markup (see the XSS defenses lesson).
Text lives in catalogs
User-facing strings are keyed text in per-locale catalogs, never literals in components. Two practices keep catalogs honest. A fallback chain looks for a key in de-AT, then de, then the default locale, and records every key not found where it was asked. Pseudo-localization replaces each string with an accented, longer, bracketed version, so hard-coded text (which stays plain) and clipped layouts (which overflow) show up in a normal build.
Figure 3. A key is searched from the specific locale to the default, and misses are recorded
How to read this: the solid path is the search order, the dotted lines are the report. A fallback that shows English to a German user is better than a blank, but only if someone reads the report.
Scenario 6 of the demo prints this behaviour and the pseudo-localized strings (examples/frontend/golden/locale-negotiation-rtl.txt). A {count} placeholder survives pseudo-localization, because the string must still format. Filling placeholders, and why one sentence needs plural forms, is the next lesson.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Negotiate on the server | First HTML in the right language and direction | The response varies by header, which affects caching |
| Let the user choose and remember it | Honours an explicit choice | Needs storage and a visible control |
| Strict lookup | Predictable, and easy to test | A fr-FR visitor gets the default if you ship only fr-CA |
| Accept a sibling region | More visitors get their language | Wording and spelling differ between regions |
| Logical properties | One stylesheet for both directions | Needs a review of icons and animations |
In practice: a storefront that greeted French customers in English
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A storefront ships in English and adds German, Canadian French and Arabic, with a catalog per locale. In the first week, customers in France write that the site is English-only, and Arabic readers write that the cart badge covers the price.
Starting architecture
Figure 4. Starting point: the locale comes from the header with a strict match, and the stylesheet has physical sides
How to read this: the red dashed edges are the two defects. The first loses the visitor's language, the second keeps the layout the same in both directions.
Options considered
| Option | What it fixes | What it costs |
|---|---|---|
Ship a fr catalog too |
Covers all French | Another catalog to review, mixed regional wording |
Same-language fallback for fr-* |
French at once for France | One rule in negotiation, a product choice to document |
| Logical properties in the stylesheet | One sheet, both directions | A review of every physical rule and icon |
The decision
| Field | Decision record |
|---|---|
| Context | Visitors from France get English, and the Arabic layout is not mirrored. |
| Decision | Negotiation tries lookup for each range in quality order, then accepts another region of the same language, then the default. A saved choice always wins. The server writes lang and dir on the root element from the chosen locale. The CSS is moved to logical properties, and a check reports any physical property. |
| Consequences, good | French visitors get French; one stylesheet, two directions. |
| Consequences, bad | The chosen region's wording may differ; icons still need manual review. |
| Revisit when | A fr-FR catalog is worth maintaining. |
Rollout and verification
- Ship the negotiation change first, with a log line that records the header, the range that matched and how (
lookup,same-languageordefault). - Pseudo-localize a staging build and click through the cart and checkout, looking for plain text and overflow.
- Run the physical-property check, then open the Arabic build and check the cart badge, the price and every arrow.
The 2 a.m. failure
A report arrives that a user in Quebec is shown English after the release (illustrative). The header reads fr-CA, which matches exactly, so the cause is elsewhere: a saved choice cookie with the value en from an earlier visit now beats the header, as designed.
First three checks: (1) log the negotiation result with its source, and see explicit; (2) check the stored value and where it was written; (3) confirm the control that sets it is visible. Mitigation: show the language control prominently and let the user clear the choice. Follow-up: record when the choice was made, and add a test where the saved value and the header disagree.
Architect's notes
- Make negotiation a pure function. Put the header, the saved choice and the supported list in; get a locale and the reason out, and log the reason.
- Write
langanddirfrom the same value. Two sources drift apart. - Prefer logical CSS from the start. Retrofitting is a review of every rule.
Common mistakes
- Treating the language as the direction.
ar-Latnis Arabic and left to right. - Using the header as the only input. MDN says a server should never override an explicit user choice.
- Reading only the first range. The match may be in the second or third.
- Hard-coding
leftandright. The page cannot mirror. - Concatenating translated fragments. Word order differs between languages (next lesson).
Key takeaways
- Internationalization is one-time engineering. Localization is per-locale content and review.
- A locale is chosen from a saved choice, the
Accept-Languageranges and a default, and the result should carry its reason. - Lookup truncates a tag from the end; it does not match sibling regions unless you add that rule.
langnames the language;dirsets the direction; direction follows the script.- Logical properties turn left and right into start and end, so one stylesheet serves both directions.
- Isolate text of unknown direction, and keep text in catalogs with a fallback chain and a missing-keys report.
Practice exercises
Exercise 1 — Starter (45 min): Add Content-Language to the negotiation result and write a test for de-AT, fr-FR and an unsupported language.
Exercise 2 — Intermediate (2 hours): Extend the CSS finder to flag margin: 0 8px 0 0 shorthands, and explain why transform: translateX(10px) cannot be fixed by renaming a property.
Exercise 3 — Advanced (half day): List ten places in a page where direction matters beyond margins, and decide for each whether to mirror it.
Related reading
In this course:
- Semantic HTML and Document Structure, the root element and what assistive technology reads.
- Modern CSS Layout and Responsive Design and CSS Architecture and Scaling, where logical values apply.
- XSS Defenses, escaping text that is inserted into markup.
- The next lesson, Message Formatting, Plurals and the Intl APIs, covers plural forms, numbers, dates and lists.