Advanced i18n: RTL Layouts and Locale Formatting
Translating strings is the easy part of going international. The hard part is everything around them: which URL a visitor should land on, how the browser's language header maps to a locale your app actually ships, what happens when the preferred language is missing, and why an Arabic layout is not a translated layout but a mirrored one. A team that only swaps dictionary values ends up with a product that reads correctly and behaves wrong â dates in the wrong order, currencies in the wrong format, and a sidebar on the wrong side of the screen.
This lesson covers the parts of internationalisation that live in routing, CSS, and formatting APIs rather than in translation files.
Prerequisites
- !Dynamic route segments and layouts
- !JSON data files and dynamic imports
- !Flexbox or grid layout fundamentals
What You'll Learn
- 1Detect, persist and redirect on locale without redirect loops
- 2Load only the dictionary a request needs
- 3Apply direction correctly, including mirrored layouts
- 4Format dates, numbers, currencies and plurals per locale
Locale is a routing decision
The first fork is whether the locale lives in the URL. Putting it there â /fr/pricing rather than a cookie-driven /pricing â costs one extra segment and buys crawlable, shareable, cacheable per-language pages. Search engines can index each version, a shared link keeps its language, and the CDN can cache each locale separately. The alternative, deciding language from a cookie or header, produces one URL with many contents, which makes caching and canonicalisation awkward from the first day.
The rule that follows is that the locale is a required segment in the layout, not an optional lookup. Every link, every generateMetadata, every redirect has to know which locale it is operating in, and threading that through props or a context is more predictable than reading a cookie in forty places.
// middleware.js â send the visitor to a locale before any page renders
import { NextResponse } from 'next/server';
const LOCALES = ['en', 'fr', 'de', 'ar'];
const DEFAULT = 'en';
export function middleware(request) {
const { pathname } = request.nextUrl;
// Anything already under a locale prefix is left alone.
if (LOCALES.some((l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`))) {
return NextResponse.next();
}
const cookie = request.cookies.get('locale')?.value;
const header = request.headers.get('accept-language')?.toLowerCase() || '';
const best = cookie || pickFrom(header) || DEFAULT;
const url = request.nextUrl.clone();
url.pathname = `/${best}${pathname === '/' ? '' : pathname}`;
return NextResponse.redirect(url);
}
export const config = {
matcher: ['/((?!_next|api|favicon.ico|.*\\..*).*)'],
};
The matcher is what keeps the redirect from looping: static files, _next assets, and API routes are excluded so a request for an image never bounces through language detection again. Persisting the choice in a cookie on the way out means the next visit starts where the visitor wants rather than where their browser header happens to point.
Loading only the dictionary you need
Bundling every language into every page means a French reader downloads Spanish and German translations they will never see. Dynamic import per locale keeps the cost proportional, and because the layout is where the locale is known, the layout is where the dictionary should load.
// lib/dictionaries.js
const dictionaries = {
en: () => import('../locales/en.json').then((m) => m.default),
fr: () => import('../locales/fr.json').then((m) => m.default),
de: () => import('../locales/de.json').then((m) => m.default),
ar: () => import('../locales/ar.json').then((m) => m.default),
};
export const getDictionary = async (locale) => {
const load = dictionaries[locale] || dictionaries.en;
return load();
};
// app/[locale]/layout.js
export default async function LocaleLayout({ children, params }) {
const { locale } = await params;
const dict = await getDictionary(locale);
const dir = ['ar', 'he'].includes(locale) ? 'rtl' : 'ltr';
return (
<html lang={locale} dir={dir}>
<body>
<nav aria-label={dict.nav.label}>
<a href={`/${locale}`}>{dict.nav.home}</a>
<a href={`/${locale}/pricing`}>{dict.nav.pricing}</a>
</nav>
<main>{children}</main>
</body>
</html>
);
}
Setting lang and dir on the root element is not a formality: screen readers pick pronunciation from lang, and the browser's own bidi algorithm picks base direction from dir. Getting either wrong makes the page unreadable to someone rather than merely unpolished.
Direction is layout, not translation
Flipping dir mirrors inline and logical properties automatically â text aligns right, padding-start becomes padding on the right, and flex rows reverse. Physical properties do not follow: margin-left, left, text-align: left, and border-left all stay where they were, which is why a half-converted RTL page looks almost right and feels broken.
/* One layout, both directions */
.sidebar {
/* Logical properties follow dir automatically */
padding-inline-start: 1.5rem;
border-inline-end: 1px solid var(--line);
margin-inline-end: 1rem;
}
/* The calendar glyph genuinely should not mirror */
.clock-icon {
/* Physical stays physical when mirroring is wrong */
transform: scaleX(1);
}
[dir='rtl'] .clock-icon {
/* Only flip the elements that represent a timeline */
transform: scaleX(-1);
}
.stack {
display: flex;
gap: 0.75rem;
/* No left or right anywhere in the rule */
}
The working habit is to write logical properties everywhere and reserve physical ones for things that represent physical reality â a clock face, a timeline arrow, a chart axis â where you decide explicitly whether mirroring is correct. Anything that renders user-generated content needs the same audit: a mirrored code block or a reversed number line is a bug you cannot fix with a dictionary.
Formatting is the API's job
Hard-coded date and number strings are the second most common internationalisation defect, after direction. Intl.DateTimeFormat, Intl.NumberFormat, and Intl.PluralRules already encode the rules for two hundred locales, including the ones that are genuinely hard: month-first versus day-first ordering, non-breaking space thousands separators, and plural categories beyond singular and plural.
// components/Localized.jsx
const number = (value, locale, options) =>
new Intl.NumberFormat(locale, options).format(value);
export function Price({ amount, currency, locale }) {
return <span>{number(amount, locale, { style: 'currency', currency })}</span>;
}
export function When({ iso, locale }) {
const text = new Intl.DateTimeFormat(locale, {
dateStyle: 'medium',
timeStyle: 'short',
timeZone: 'UTC',
}).format(new Date(iso));
// Machine-readable value stays stable; humans see the localized form.
return <time dateTime={iso}>{text}</time>;
}
export function CartCount({ count, locale }) {
const rules = new Intl.PluralRules(locale).select(count);
const forms = { one: 'item', other: 'items', few: 'items', many: 'items' };
return <span>{number(count, locale)} {forms[rules]}</span>;
}
Notice the explicit timeZone. Formatting an instant in the viewer's local zone is usually right, but for anything legal or operational â a billing period, a scheduled maintenance window â an unqualified date string is ambiguous the moment two readers are in different zones. Decide per component and make the choice visible in the markup.
| Data | Use | Do not |
|---|---|---|
| Timestamps | Intl.DateTimeFormat with an explicit zone | Concatenate month, day and year by hand |
| Money | Intl.NumberFormat with style: 'currency' | Prepend a currency symbol string |
| Percentages | Intl.NumberFormat with style: 'percent' | Multiply and append a sign manually |
| Plurals | Intl.PluralRules plus a form map | Use a ternary on the count |
| Units | Intl.NumberFormat with unit style | Hard-code "km" or "lb" in copy |
The failure modes that only appear in production
Internationalisation bugs are unusually good at hiding in development, because the developer's own locale is usually the one that was written first and tested most. Redirect loops are the first class: a middleware that redirects on locale without excluding _next assets will happily bounce an image request, and a page that redirects based on a cookie set after the redirect will oscillate until the browser gives up. Match only page paths, set the cookie outside the redirect branch, and test with cookies both present and absent.
Missing keys are the second class. Falling back to the default locale means a French reader sees English text and nobody notices until a customer does, which is why a key-diffing build step matters more than any runtime warning. Plurals are the third: Intl.PluralRules returns categories such as one, few, many and zero depending on the language, and a dictionary that only contains one and other will produce grammatical nonsense for a language that needs few. Always select the category first and look the form up; never branch on the count in the template.
Finally, remember that not everything lives in a JSON file. Text baked into an image, a date format hard-coded in a chart library, and an email built from string concatenation are all translatable content that no dictionary will reach. Put those on the checklist alongside the strings, because they are the ones that survive a translation pass untouched.
What to translate, and what to leave
Not every string deserves a locale file. UI labels, error messages, marketing copy, and email templates do. Machine-generated identifiers, user-provided content, and anything that is really a brand name generally should not be translated, because doing so breaks matching against a database value or creates confusion about what the product is called.
Organise files by locale at the top level and by namespace inside, so a translator can work on fr/errors.json without opening the navigation file, and so a missing key is a small, localised gap rather than an empty page. A build step that diffs the default locale against every other one will catch incomplete translations before they ship â keys silently falling back to English are the sort of defect that survives review for months.
Common Mistakes
Redirecting on locale without excluding static assets and API routes
Fix: Match only page paths in middleware so images and data endpoints never enter the redirect loop.
Using physical CSS properties in a layout that must support RTL
Fix: Switch to padding-inline, margin-inline, inset-inline and text-align where the logical version exists.
Bundling every dictionary into the layout
Fix: Dynamic import per locale so a reader only downloads the language they selected.
Formatting dates with toLocaleString and no options or zone
Fix: Pass explicit style and timeZone so output is predictable and unambiguous across regions.
Best Practices
- Put the locale in the URL and persist the preference in a cookie for the next visit
- Set lang and dir on the root element from the route, not from a client-side effect
- Route every user-facing number, date and plural through Intl with the active locale
- Diff locale files in CI so a missing key fails the build instead of shipping English text
Key Takeaways
- Locale in the URL gives crawlable, cacheable, shareable pages; a cookie decides only where to redirect.
- Load the dictionary for one locale with a dynamic import, in the layout that knows the locale.
- RTL requires logical CSS properties; translating strings alone leaves the layout mirrored incorrectly.
- Intl.DateTimeFormat, NumberFormat and PluralRules encode rules you should never re-implement.
- Set lang and dir on the root element so assistive technology and bidi rendering both behave.