Frontend development · Intermediate · 30 min
Translate an interface and format numbers and dates with Intl
By Padding · Updated 18 Nov 2026
Modern browsers · ECMAScript Intl API (ECMA-402) · Node.js 26.13.1 LTS · Playwright 1.65.1 · node:26 image
You will have a small basket page in English, French and Swahili, with an Arabic right-to-left preview, that picks the visitor's language, switches without a reload and formats money, dates, plurals and relative times with the built-in Intl API.
On this page
A page that only speaks English loses people who would happily use it in French, Swahili or Arabic. Translating the words is half the work. The other half is the values around them: 4,850.50 in Nairobi is 4 850,50 in Paris, "1 item" and "5 items" follow different rules in every language, and Arabic runs from right to left, so a border on the left of a panel ends up on the wrong side.
Browsers already carry the locale data for most of this in the Intl API, which is part of JavaScript. In this tutorial you build a small basket page and translate it with no i18n library: one JSON message file per language, a t() function that fills in placeholders, a language picked from the browser's preferences with a switcher to change it, and Intl.NumberFormat, Intl.DateTimeFormat, Intl.PluralRules and Intl.RelativeTimeFormat for the values. You finish with an Arabic preview that mirrors correctly thanks to CSS logical properties, and a Playwright test that checks all of it.
Because the locale data ships with the browser, the page downloads only the one message file it needs, a few hundred bytes. That matters on a low-end Android phone with a prepaid data bundle, where a full locale library could cost more than the page itself. The design side of this work, deciding how each value should look, is covered in show dates, times, phone numbers and money clearly; this tutorial is the code that carries it out.
Commands are shown for a Linux or macOS shell. On Windows, use WSL or create the files in your editor with the same contents.
Step 1 · Serve the starter page
Make a demo folder and write the page in English. Every piece of fixed text carries a data-i18n attribute naming its message key, and the values that change (the item count, total, dates) have ids so a script can fill them in. The English text in the HTML is what people see if the script fails to load.
mkdir -p ~/intl-basket-demo/locales
cd ~/intl-basket-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Your basket</title>
<link rel="stylesheet" href="style.css">
<script type="module" src="app.js"></script>
</head>
<body>
<main>
<header class="bar">
<h1 data-i18n="app.title">Your basket</h1>
<label class="switcher">
<span data-i18n="lang.label">Language</span>
<select id="language">
<option value="en" lang="en">English</option>
<option value="fr" lang="fr">Français</option>
<option value="sw" lang="sw">Kiswahili</option>
<option value="ar" lang="ar">العربية</option>
</select>
</label>
</header>
<section class="summary">
<p id="count">3 items</p>
<div class="stepper">
<button type="button" id="remove" data-i18n="remove">Remove one</button>
<button type="button" id="add" data-i18n="add">Add one</button>
</div>
<p id="total">Total: KES 4,850.50</p>
<p id="delivery">Delivery on Wednesday 9 December 2026</p>
<p id="updated">Prices updated 5 minutes ago</p>
</section>
<section class="fees">
<h2 data-i18n="fees.heading">Delivery fees</h2>
<ul id="fees"></ul>
</section>
</main>
</body>
</html>
HTML
cat > style.css <<'CSS'
:root { --ink: #1b1f24; --muted: #5a6270; --line: #d9dce1; --accent: #0f5e5a; --canvas: #f6f7f8; }
* { box-sizing: border-box; }
body { margin: 0; background: var(--canvas); color: var(--ink); font-family: system-ui, sans-serif; line-height: 1.5; }
main { max-width: 32rem; margin: 0 auto; padding: 1rem; }
.bar { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: end; justify-content: space-between; }
h1 { margin: 0; font-size: 1.5rem; }
h2 { font-size: 1.125rem; margin: 1.5rem 0 0.5rem; }
.switcher { display: grid; gap: 0.25rem; font-size: 0.875rem; }
select, button { font: inherit; min-height: 2.75rem; padding: 0.25rem 0.75rem; }
.summary { margin-top: 1.5rem; padding-left: 1rem; border-left: 4px solid var(--accent); text-align: left; }
.stepper { display: flex; flex-wrap: wrap; gap: 0.5rem; }
#updated { color: var(--muted); font-size: 0.875rem; }
.fees ul { list-style: none; margin: 0; padding: 0; }
.fees li { display: flex; justify-content: space-between; gap: 1rem; padding: 0.5rem 0; border-bottom: 1px solid var(--line); }
.price { font-variant-numeric: tabular-nums; }
CSS
cat > app.js <<'JS'
console.log('app.js loaded');
JSThe options in the language switcher are written in their own language, each with its own lang attribute. Someone who reads only Swahili looks for "Kiswahili", not "Swahili", and a screen reader uses the lang to pronounce each name correctly. The .summary panel uses padding-left, border-left and text-align: left on purpose; Step 6 shows why that is a problem.
The page will load JSON files with fetch() and load app.js as a module, and neither works from a file:// address. Write a small server with Node's built-in http module that serves the demo folder, including the locales subfolder:
cd ~/intl-basket-demo
cat > serve.mjs <<'JS'
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { extname, join } from 'node:path';
const types = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
};
const port = Number(process.env.PORT ?? 8080);
createServer(async (req, res) => {
const path = new URL(req.url, 'http://localhost').pathname;
const file = path === '/' ? 'index.html' : path.slice(1);
const type = types[extname(file)];
if (!type || file.includes('..')) return res.writeHead(404).end('Not found');
try {
const body = await readFile(join(import.meta.dirname, file));
res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store' }).end(body);
} catch {
res.writeHead(404).end('Not found');
}
}).listen(port, '127.0.0.1', () => console.log(`Serving on http://127.0.0.1:${port}`));
JSStart it in a second terminal and leave it running for the rest of the tutorial:
cd ~/intl-basket-demo
node serve.mjsCheck it worked
The server terminal prints Serving on http://127.0.0.1:8080. Open that address: you see "Your basket" with a Language menu beside it, a panel with a teal bar on its left reading "3 items", two buttons, the total, the delivery date and a grey "Prices updated" line, then an empty Delivery fees heading. The browser console (F12, then Console) shows app.js loaded. If port 8080 is taken, start the server with PORT=8081 node serve.mjs and use that port everywhere below.
Step 2 · Write the message files and a t() function
Each language gets one JSON file of messages, keyed by the same names you used in data-i18n. Placeholders in braces, such as {amount}, mark where a value goes. Keep the whole sentence in the message, including the placeholder, because word order changes between languages: English says "3 items" and Swahili says "vipengee 3".
The items message is an object, not a string. It holds one wording per plural category, which Step 5 explains. English and Swahili need two forms; French has a third, many, for some large round numbers, and Arabic needs six.
cd ~/intl-basket-demo/locales
cat > en.json <<'JSON'
{
"app.title": "Your basket",
"lang.label": "Language",
"items": { "one": "{count} item", "other": "{count} items" },
"remove": "Remove one",
"add": "Add one",
"total": "Total: {amount}",
"delivery": "Delivery on {date}",
"updated": "Prices updated {when}",
"fees.heading": "Delivery fees",
"fees.lagos": "Lagos",
"fees.nairobi": "Nairobi",
"fees.paris": "Paris"
}
JSON
cat > fr.json <<'JSON'
{
"app.title": "Votre panier",
"lang.label": "Langue",
"items": { "one": "{count} article", "other": "{count} articles" },
"remove": "En retirer un",
"add": "En ajouter un",
"total": "Total\u202F: {amount}",
"delivery": "Livraison le {date}",
"updated": "Prix mis à jour {when}",
"fees.heading": "Frais de livraison",
"fees.lagos": "Lagos",
"fees.nairobi": "Nairobi",
"fees.paris": "Paris"
}
JSON
cat > sw.json <<'JSON'
{
"app.title": "Kikapu chako",
"lang.label": "Lugha",
"items": { "one": "kipengee {count}", "other": "vipengee {count}" },
"remove": "Ondoa kimoja",
"add": "Ongeza kimoja",
"total": "Jumla: {amount}",
"delivery": "Tarehe ya kufikishwa: {date}",
"updated": "Bei zilisasishwa {when}",
"fees.heading": "Ada za usafirishaji",
"fees.lagos": "Lagos",
"fees.nairobi": "Nairobi",
"fees.paris": "Paris"
}
JSON
cat > ar.json <<'JSON'
{
"app.title": "سلتك",
"lang.label": "اللغة",
"items": {
"zero": "لا توجد عناصر",
"one": "عنصر واحد",
"two": "عنصران",
"few": "{count} عناصر",
"many": "{count} عنصرًا",
"other": "{count} عنصر"
},
"remove": "أزل عنصرًا",
"add": "أضف عنصرًا",
"total": "المجموع: {amount}",
"delivery": "التسليم يوم {date}",
"updated": "تم تحديث الأسعار {when}",
"fees.heading": "رسوم التوصيل",
"fees.lagos": "لاغوس",
"fees.nairobi": "نيروبي",
"fees.paris": "باريس"
}
JSONFrench typography puts a no-break space (often the narrow one, U+202F) before a colon, so the colon never wraps onto a line of its own. The file writes it as the escape \u202F, because the character itself looks like an ordinary space in an editor and is easy to replace by accident; JSON.parse turns the escape back into the real character. House styles differ on which space to use, so follow the one your translator or style guide prefers. Treat the French, Swahili and Arabic files as a starting point: have a fluent speaker review every message file before you ship it, and give translators the whole file, not single strings, so they can see context.
Now write i18n.js, the module that loads a file and looks messages up. It stores the full locale tag the visitor uses, such as sw-KE or en-NG, and loads messages by the language part alone (sw, en). The tag drives number and date formats; the language picks the words. English is always loaded as the fallback, so a message missing from another file shows in English rather than as a blank.
cd ~/intl-basket-demo
cat > i18n.js <<'JS'
import { pluralCategory } from './plural.js';
export const languages = ['en', 'fr', 'sw', 'ar'];
const fallback = 'en';
const loaded = new Map();
let tag = fallback;
export function languageOf(localeTag) {
try {
return new Intl.Locale(localeTag).language;
} catch {
return null;
}
}
// The first tag whose language we have messages for, or English.
export function matchTag(candidates) {
return candidates.find((c) => c && languages.includes(languageOf(c))) ?? fallback;
}
async function load(language) {
if (!loaded.has(language)) {
const response = await fetch(`locales/${language}.json`);
if (!response.ok) throw new Error(`Could not load ${language}.json (${response.status})`);
loaded.set(language, await response.json());
}
}
export async function setLocale(next) {
await load(fallback);
await load(languageOf(next));
tag = next;
}
export const locale = () => tag;
export const language = () => languageOf(tag);
export function t(key, params = {}) {
let message = loaded.get(language())?.[key] ?? loaded.get(fallback)?.[key] ?? key;
if (typeof message === 'object') {
message = message[pluralCategory(tag, params.count)] ?? message.other;
}
return message.replace(/\{(\w+)\}/g, (whole, name) => {
if (!(name in params)) return whole;
const value = params[name];
return typeof value === 'number' ? new Intl.NumberFormat(tag).format(value) : String(value);
});
}
JS
cat > plural.js <<'JS'
// A first attempt: the English rule. Step 5 replaces it.
export function pluralCategory(locale, count) {
return count === 1 ? 'one' : 'other';
}
JSt() does three things. It finds the message in the current language, then in English, then falls back to the key itself so a missing translation is obvious on screen. If the message has plural forms, it picks one. Then it replaces each {name} with the matching parameter, formatting numbers for the locale so {count} shows 1 250 in French. A placeholder with no parameter is left as it is, which makes a typo easy to spot.
Check it worked
Open http://127.0.0.1:8080/locales/sw.json: the browser shows the Swahili messages, with no garbled characters. Then go back to the page, open the console and paste:
const { setLocale, t } = await import('/i18n.js');
await setLocale('sw-KE');
[t('total', { amount: 'Ksh 10' }), t('items', { count: 5 }), t('missing.key')]The console shows ['Jumla: Ksh 10', 'vipengee 5', 'missing.key']. If you see a SyntaxError mentioning JSON instead, one of the message files has a missing comma or quote.
Step 3 · Pick a language and switch without a reload
Now write app.js. On load it chooses a language in this order: one the visitor chose before on this device, then the first supported entry in navigator.languages, the browser's list of preferred languages in order, then English. When someone picks from the menu, it loads that file, redraws every string in place and remembers the choice.
It also sets two attributes on <html>. lang tells screen readers which voice and pronunciation to use, helps browsers pick fonts and hyphenation, and tells translation tools what the page already is. dir sets the text direction: rtl for Arabic, ltr for the others.
The formatting helpers live in their own file, format.js. Start with the naive versions most code begins with, so you can see what goes wrong:
cd ~/intl-basket-demo
cat > format.js <<'JS'
// Naive versions: they ignore the locale. Step 4 replaces them.
export const money = (locale, amount, currency) => `${currency} ${amount}`;
export const longDate = (locale, date) => date.toDateString();
export const ago = (locale, date) => `${Math.round((Date.now() - date) / 60000)} minutes ago`;
JS
cat > app.js <<'JS'
import { languages, languageOf, matchTag, setLocale, locale, language, t } from './i18n.js';
import { money, longDate, ago } from './format.js';
const rtlLanguages = new Set(['ar', 'fa', 'he', 'ur']);
const basket = {
count: 3,
total: 4850.5,
currency: 'KES',
deliveryOn: new Date('2026-12-09T09:00:00+03:00'),
timeZone: 'Africa/Nairobi',
pricesUpdated: new Date(Date.now() - 5 * 60 * 1000),
};
const fees = [
{ city: 'fees.lagos', amount: 3500, currency: 'NGN' },
{ city: 'fees.nairobi', amount: 350, currency: 'KES' },
{ city: 'fees.paris', amount: 6.5, currency: 'EUR' },
];
const picker = document.querySelector('#language');
const preferred = () => [...(navigator.languages ?? []), navigator.language];
// Keep the visitor's region (sw-KE, en-NG) when they pick its language.
const tagFor = (lang) => preferred().find((tag) => languageOf(tag) === lang) ?? lang;
function savedLanguage() {
try { return localStorage.getItem('language'); } catch { return null; }
}
function saveLanguage(lang) {
try { localStorage.setItem('language', lang); } catch { /* private mode: not remembered */ }
}
function render() {
const root = document.documentElement;
root.lang = locale();
root.dir = rtlLanguages.has(language()) ? 'rtl' : 'ltr';
picker.value = language();
document.title = t('app.title');
for (const el of document.querySelectorAll('[data-i18n]')) el.textContent = t(el.dataset.i18n);
document.querySelector('#count').textContent = t('items', { count: basket.count });
document.querySelector('#remove').disabled = basket.count === 0;
document.querySelector('#total').textContent = t('total', { amount: money(locale(), basket.total, basket.currency) });
document.querySelector('#delivery').textContent = t('delivery', { date: longDate(locale(), basket.deliveryOn, basket.timeZone) });
document.querySelector('#updated').textContent = t('updated', { when: ago(locale(), basket.pricesUpdated) });
document.querySelector('#fees').replaceChildren(...fees.map((fee) => {
const li = document.createElement('li');
const city = document.createElement('span');
city.textContent = t(fee.city);
const price = document.createElement('span');
price.className = 'price';
price.textContent = money(locale(), fee.amount, fee.currency);
li.append(city, price);
return li;
}));
}
picker.addEventListener('change', async () => {
await setLocale(tagFor(picker.value));
saveLanguage(picker.value);
render();
});
document.querySelector('#remove').addEventListener('click', () => {
basket.count = Math.max(0, basket.count - 1);
render();
});
document.querySelector('#add').addEventListener('click', () => {
basket.count += 1;
render();
});
const saved = savedLanguage();
await setLocale(languages.includes(saved) ? tagFor(saved) : matchTag(preferred()));
render();
JSSome details worth knowing:
- The tag, not only the language. If the browser prefers
sw-KE, the page uses Swahili messages and keepssw-KEfor formatting, so prices and dates follow Kenyan conventions. Someone onen-NGgets English words with Nigerian formats. Picking a language from the menu keeps the visitor's region when the languages match. - No reload. Changing language replaces text in the existing page, so whatever the visitor typed or scrolled to stays put.
- Saving the choice.
localStorageremembers it on this device only, and every access is wrapped intry, because some private windows block storage. The page still works; it forgets the choice. For a fuller pattern, see remember user settings with localStorage. - Top-level
await. The last two lines wait for the messages before the first render. Module scripts allowawaitoutside a function.
Check it worked
Reload the page. It appears in your browser's language if that is English, French or Swahili, and in English otherwise. Choose Kiswahili from the menu: the heading becomes "Kikapu chako", the count "vipengee 3", and the fees list redraws (it looks the same for now, because the city names are the same in Swahili and the prices are not formatted yet), without the page flashing white or scrolling back to the top. In the developer tools' Elements (or Inspector) panel, the <html> element now has lang="sw", or a regional tag such as sw-KE if your browser lists one. Reload: the page stays in Swahili.
Now choose Français and look at the values. The words are French, but the total reads Total : KES 4850.5, the date is in English and the last line says Prix mis à jour 5 minutes ago. Choose العربية: the text moves to the right, but the teal bar stays on the left. The next three steps fix each of these.
Step 4 · Format money, dates and relative times with Intl
Replace format.js with versions that take the locale seriously:
cd ~/intl-basket-demo
cat > format.js <<'JS'
export function money(locale, amount, currency) {
return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(amount);
}
export function longDate(locale, date, timeZone) {
return new Intl.DateTimeFormat(locale, { dateStyle: 'full', timeZone }).format(date);
}
const units = [['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1]];
export function ago(locale, date, now = Date.now()) {
const seconds = Math.round((date - now) / 1000);
const [unit, size] = units.find(([, s]) => Math.abs(seconds) >= s) ?? units.at(-1);
return new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(Math.round(seconds / size), unit);
}
JSWhat each one handles for you:
Intl.NumberFormatwithstyle: 'currency'places the symbol or code, the grouping separator and the decimal mark the way the locale expects, and uses the right number of decimal places for the currency. The currency is always yours to pass: the locale says how to write money, never which money it is. A price in naira stays in naira when a Kenyan visitor views it. By default the format shows a symbol where the locale has an unambiguous one and the ISO code otherwise, so the same 3,500 naira shows as₦3,500.00foren-NGandNGN 3,500.00foren-GB. PasscurrencyDisplay: 'code'if you want the code everywhere, for example on a page that mixes currencies from many countries.Intl.DateTimeFormatwithdateStyle: 'full'writes the weekday and month as words in the right order. Always pass atimeZonefor a date tied to a place, here the shop in Nairobi; without one, the visitor's own time zone is used and a delivery at 01:00 in Nairobi would show as the previous day in Lagos or Paris.Intl.RelativeTimeFormatturns-5minutes into "5 minutes ago", "il y a 5 minutes" or "dakika 5 zilizopita". Theago()helper chooses the largest unit that fits.numeric: 'auto'allows words such as "yesterday" and "now" in place of "1 day ago" and "0 seconds ago".
French formatting uses a narrow no-break space (U+202F) to group thousands, 4 850,50 KES. It looks like a space but is a different character, so a test that compares with a typed space fails. Compare after normalising whitespace, as the test in Step 7 does. Arabic output can start with an invisible right-to-left mark (U+200F), which keeps the number and currency in the right order inside Arabic text.
Check it worked
Reload with Kiswahili chosen. The total reads something like Jumla: Ksh 4,850.50 (with a sw-KE browser; plain sw may show KES), the delivery line ends Jumatano, 9 Desemba 2026, and the fees read NGN 3,500.00, Ksh 350.00 and € 6.50 or close to it. Choose Français: Total : 4 850,50 KES, Livraison le mercredi 9 décembre 2026 and Prix mis à jour il y a 5 minutes. Exact symbols and spacing come from the locale data in your browser and can differ slightly between browsers, which is one more reason not to build these strings by hand.
Step 5 · Choose plural forms with Intl.PluralRules
Click "En retirer un" until the French count reaches zero. It reads 0 articles, which is wrong: French uses the singular for 0 as well as 1, so it should be 0 article. Switch to Arabic and set the count to 2: it shows 2 عنصر, but Arabic has a dual form, عنصران. The naive rule in plural.js is English grammar applied to every language.
Languages fall into up to six plural categories, named zero, one, two, few, many and other. English and Swahili use one and other; French uses one, many and other, and draws the line for one in a different place; Arabic uses all six. Intl.PluralRules knows which category a number falls into for each locale, using the Unicode CLDR rules. Replace plural.js:
cd ~/intl-basket-demo
cat > plural.js <<'JS'
const rules = new Map();
export function pluralCategory(locale, count) {
if (!rules.has(locale)) rules.set(locale, new Intl.PluralRules(locale));
return rules.get(locale).select(count);
}
JSCreating an Intl.PluralRules object loads locale data, so the function keeps one per locale and reuses it. select(count) returns the category name, and t() picks the message with that name, falling back to other if a translator left one out. fr.json leaves out many on purpose: "1 000 000 articles" uses the same wording as other, so a French count of 1 000 000 gets category many, finds no many message and falls back to other. Add a many form only when a translator wants different wording for those numbers.
Some results to expect, from Node.js 26's locale data:
- English and Swahili:
onefor 1,otherfor 0, 2 and 5. - French:
onefor 0 and 1,manyfor some large round numbers such as 1 000 000,otherfor the rest. - Arabic:
zerofor 0,onefor 1,twofor 2,fewfor 3 to 10,manyfor 11 to 99,otherfor 100.
Plural rules decide the form of the words around a number. They do not decide whether a sentence is needed at all, so "Your basket is empty" can still be its own message if your design calls for it.
Check it worked
Reload in French and click "En retirer un" three times: the count reads 0 article, and the button turns grey because the basket cannot go below zero. In Swahili, remove two to see kipengee 1, then add one to see vipengee 2. In Arabic, start from three items and remove one: the count reads عنصران; remove one more for عنصر واحد and another for لا توجد عناصر.
Step 6 · Preview Arabic right to left with logical CSS properties
With dir="rtl" on <html>, the browser already reverses the flow of text and of flex rows: the heading moves to the right, the language menu to the left, and in the fees list the city sits on the right with the price on the left. What does not flip is any CSS written in physical directions. The .summary panel still has padding-left, border-left and text-align: left, so in Arabic the accent bar is on the wrong side and the text is pushed away from where Arabic readers start.
CSS logical properties describe the start and end of a line instead of left and right. inline-start is the left in English and the right in Arabic. Rewrite style.css with logical properties for the panel, and use the same habit for margins, padding and positioning everywhere else:
cd ~/intl-basket-demo
cat > style.css <<'CSS'
:root { --ink: #1b1f24; --muted: #5a6270; --line: #d9dce1; --accent: #0f5e5a; --canvas: #f6f7f8; }
* { box-sizing: border-box; }
body { margin: 0; background: var(--canvas); color: var(--ink); font-family: system-ui, sans-serif; line-height: 1.5; }
main { max-inline-size: 32rem; margin-inline: auto; padding: 1rem; }
.bar { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: end; justify-content: space-between; }
h1 { margin: 0; font-size: 1.5rem; }
h2 { font-size: 1.125rem; margin-block: 1.5rem 0.5rem; }
.switcher { display: grid; gap: 0.25rem; font-size: 0.875rem; }
select, button { font: inherit; min-block-size: 2.75rem; padding-block: 0.25rem; padding-inline: 0.75rem; }
.summary { margin-block-start: 1.5rem; padding-inline-start: 1rem; border-inline-start: 4px solid var(--accent); text-align: start; }
.stepper { display: flex; flex-wrap: wrap; gap: 0.5rem; }
#updated { color: var(--muted); font-size: 0.875rem; }
.fees ul { list-style: none; margin: 0; padding: 0; }
.fees li { display: flex; justify-content: space-between; gap: 1rem; padding-block: 0.5rem; border-block-end: 1px solid var(--line); }
.price { font-variant-numeric: tabular-nums; }
:lang(ar) { line-height: 1.7; }
CSSThree things to know:
- Set
diron<html>, not with CSS. Thedirectionproperty exists, but the HTMLdirattribute carries meaning that screen readers and translation tools also read.app.jsalready sets it. :lang(ar)matches every element in an Arabic page, here giving Arabic script a little more line height for its taller letter shapes. The same selector is how you would choose a font for a script your main font lacks.- Text you do not control. A name or address typed by a user can be in a different direction from the page around it. Wrap such values in
<bdi>so they cannot reorder the punctuation next to them.
Check it worked
Reload and choose العربية. The teal bar is now on the right of the panel and the text lines up against it, the heading reads "سلتك" at the top right, and the fees list shows each city on the right with its price on the left. Switch back to English: the bar returns to the left, with no separate right-to-left stylesheet. Narrow the window to phone width: nothing scrolls sideways in either direction.
Step 7 · Test every language with Playwright
Install Playwright, which drives a real browser from a script, into the demo folder. --with-deps also installs the system libraries Chromium needs on Linux, which can ask for your password:
cd ~/intl-basket-demo
npm init -y > /dev/null
npm install playwright@1.65.1
npx playwright install --with-deps chromiumThe test opens the page as browsers with different language preferences, using Playwright's locale option, which sets navigator.language and navigator.languages. Values whose exact characters come from locale data are checked for their stable parts (the digits, the month name), so a small change in a browser's data does not break the test.
cd ~/intl-basket-demo
cat > test-intl.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
const url = `http://127.0.0.1:${process.env.PORT ?? 8080}/`;
const browser = await chromium.launch();
const errors = [];
async function open(locale) {
const context = await browser.newContext({ locale, viewport: { width: 360, height: 740 } });
const page = await context.newPage();
page.on('pageerror', (e) => errors.push(e.message));
await page.goto(url);
await page.waitForLoadState('networkidle');
return page;
}
// Collapse every kind of space (no-break, narrow no-break) to a plain one.
const text = async (page, selector) =>
(await page.locator(selector).textContent()).replace(/\s+/g, ' ').trim();
const attr = (page, name) => page.locator('html').getAttribute(name);
// A Swahili browser in Kenya gets Swahili words and Kenyan formats.
const page = await open('sw-KE');
assert.equal(await attr(page, 'lang'), 'sw-KE');
assert.equal(await attr(page, 'dir'), 'ltr');
assert.equal(await page.title(), 'Kikapu chako');
assert.equal(await page.locator('#language').inputValue(), 'sw');
assert.equal(await text(page, '#count'), 'vipengee 3');
assert.match(await text(page, '#total'), /^Jumla: .*4,850\.50/);
assert.match(await text(page, '#delivery'), /9 Desemba 2026$/);
await page.getByRole('button', { name: 'Ondoa kimoja' }).click();
await page.getByRole('button', { name: 'Ondoa kimoja' }).click();
assert.equal(await text(page, '#count'), 'kipengee 1');
// Switching to French changes the same document, with French plurals.
await page.evaluate(() => { window.sameDocument = true; });
await page.getByLabel('Lugha').selectOption('fr');
await page.waitForFunction(() => document.documentElement.lang === 'fr');
assert.equal(await page.evaluate(() => window.sameDocument), true, 'no reload');
assert.equal(await text(page, 'h1'), 'Votre panier');
assert.equal(await text(page, '#count'), '1 article');
await page.getByRole('button', { name: 'En retirer un' }).click();
assert.equal(await text(page, '#count'), '0 article', 'French uses the singular for 0');
assert.ok(await page.getByRole('button', { name: 'En retirer un' }).isDisabled());
assert.equal(await text(page, '#total'), 'Total : 4 850,50 KES');
assert.equal(await text(page, '#delivery'), 'Livraison le mercredi 9 décembre 2026');
assert.equal(await text(page, '#updated'), 'Prix mis à jour il y a 5 minutes');
// Arabic: right to left, logical CSS, all six plural forms available.
await page.getByLabel('Langue').selectOption('ar');
await page.waitForFunction(() => document.documentElement.dir === 'rtl');
assert.equal(await attr(page, 'lang'), 'ar');
assert.equal(await text(page, '#count'), 'لا توجد عناصر');
await page.getByRole('button', { name: 'أضف عنصرًا' }).click();
await page.getByRole('button', { name: 'أضف عنصرًا' }).click();
assert.equal(await text(page, '#count'), 'عنصران', 'Arabic dual');
const border = await page.locator('.summary').evaluate((el) => {
const s = getComputedStyle(el);
return [s.borderLeftWidth, s.borderRightWidth];
});
assert.deepEqual(border, ['0px', '4px'], 'accent bar on the right');
const overflow = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth);
assert.equal(overflow, false, 'no sideways scrolling');
// The choice is remembered on reload.
await page.reload();
await page.waitForLoadState('networkidle');
assert.equal(await attr(page, 'dir'), 'rtl');
assert.equal(await text(page, 'h1'), 'سلتك');
// A regional French tag is kept for formatting.
const canada = await open('fr-CA');
assert.equal(await attr(canada, 'lang'), 'fr-CA');
assert.equal(await text(canada, 'h1'), 'Votre panier');
// An unsupported language falls back to English.
const german = await open('de-DE');
assert.equal(await attr(german, 'lang'), 'en');
assert.equal(await text(german, '#count'), '3 items');
assert.match(await text(german, '#updated'), /^Prices updated 5 minutes ago$/);
assert.deepEqual(errors, [], 'no script errors');
await browser.close();
console.log('PASS: the basket speaks English, French, Swahili and Arabic');
JS
node test-intl.mjsThe buttons and the menu are found by their accessible names in each language ("Ondoa kimoja", "Lugha"), so a missing translation shows up as a failed test, not as a quiet English word in a Swahili page.
Check it worked
The last line of output is PASS: the basket speaks English, French, Swahili and Arabic. To see it fail for the right reason, change plural.js back to the one-line English rule from Step 2 and run node test-intl.mjs again: it stops with an AssertionError about 0 article. Restore the Intl.PluralRules version and the test passes.
Step 8 · Clean up
Stop the server with Ctrl+C in its terminal, then remove the demo folder, which also removes the local Playwright install. The browser Playwright downloaded stays in its shared cache; npx playwright uninstall removes that too if you no longer need it.
cd ~
rm -rf ~/intl-basket-demoCheck it worked
ls ~/intl-basket-demo reports that there is no such file or directory, and http://127.0.0.1:8080 no longer loads in your browser.
Next steps
- Decide how each value should look before you code it, in show dates, times, phone numbers and money clearly.
- Make layouts survive French and Swahili text that runs longer than English in design for translation and longer text.
- Go back over finding and changing elements, which
render()relies on, in select and change page elements with the DOM. - Store more than the language choice in remember user settings with localStorage.
Related tutorials
- Show dates, times, phone numbers and money clearlyYou will have a formatting table that fixes how dates, times, time zones, phone numbers and prices appear in three locales, and the Larkfield booking screens updated to follow it.
- Select and change page elements with the DOMYou will build a reading-list page whose script finds, changes, adds and removes elements, then renders the whole list from an array through a template and re-renders it when the array changes.
- Design for translation and longer textYou will have the Larkfield Clinic booking screens tested with pseudo-localised text up to twice as long, fixed wherever they broke, and a localisation note that tells translators what each string is for and how much room it has.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials