#Localization
Alepha provides $dictionary for registering translations and useI18n for accessing them in React components. Translations are lazy-loaded per language and support SSR with cookie-based language selection and Accept-Language autodetection.
#Setup
Register translation dictionaries as class properties. The property name determines the language code.
1import { $dictionary } from "alepha/react/i18n";2 3class App {4 en = $dictionary({ lazy: () => import("./translations/en.ts") });5 fr = $dictionary({ lazy: () => import("./translations/fr.ts") });6}
Each translation file exports a default object mapping keys to strings:
1// translations/en.ts2export default {3 hello: "Hello",4 welcome: "Welcome, $1",5 items_count: "$1 items",6};
1// translations/fr.ts2export default {3 hello: "Bonjour",4 welcome: "Bienvenue, $1",5 items_count: "$1 elements",6};
Interpolation uses positional placeholders: $1, $2, $3, etc. A placeholder can appear several times, and one with no matching argument is left as written.
Register the i18n module in your web module's imports: AlephaReactI18n from alepha/react/i18n. It is required as soon as @alepha/ui components are mounted, even in a single-language app with no dictionary, because every @alepha/ui string goes through useI18n(). Without it the server render looks right and hydration fails in the browser.
#$dictionary Options
| Option | Type | Description |
|---|---|---|
lazy |
() => Promise<{ default: T }> |
Async loader for the translation module. |
lang |
string |
Language code. Defaults to the property name. |
name |
string |
Dictionary name. Defaults to the property name. |
#Multiple Dictionaries Per Language
You can split translations across files by using the lang option:
1class App { 2 enCommon = $dictionary({ 3 lang: "en", 4 lazy: () => import("./translations/en-common.ts"), 5 }); 6 7 enDashboard = $dictionary({ 8 lang: "en", 9 lazy: () => import("./translations/en-dashboard.ts"),10 });11}
All dictionaries for the same language are merged. Key lookups search all dictionaries for the current language.
#Translating @alepha/ui
The components in @alepha/ui call tr() with English defaults - dialogs say "Cancel / Confirm", tables announce "Open row actions". A default is not a translation: until you define the key, a French application shows English there, and setting the browser locale changes nothing because the browser language was never the problem.
@alepha/ui ships a French record you spread into your own catalogue:
1import { uiFr } from "@alepha/ui/i18n/fr"; 2 3class AppI18n { 4 fr = $dictionary({ 5 lazy: async () => ({ 6 default: { 7 ...uiFr, 8 // your own keys after, so they win on any collision 9 "nav.home": "Accueil",10 },11 }),12 });13}
It is a plain object rather than a $dictionary because @alepha/ui is a component library with no module of its own - nothing to register into.
uiFr covers every key the package asks for - tr() calls and the labelKey / groupKey declarations below - across dialogs, tables, generated forms and controls, the auth screens, the account kit, and the whole @alepha/ui/admin back office. A test asserts that parity in both directions, so a component that gains a key fails the suite until the translation lands: a missing key would otherwise fall back to its English default, which looks deliberate and is how an entire back office once stayed in English inside a French application.
If your fallbackLang is not English, also spread uiEn into your English catalogue. A lookup tries the active language, then the fallback language, and only then the component's default: with fallbackLang: "fr", an English visitor whose en catalogue lacks a key reads it in French, never reaching the English default.
1import { uiEn } from "@alepha/ui/i18n/en";2 3class AppI18n {4 en = $dictionary({5 lazy: async () => ({ default: { ...uiEn, "nav.home": "Home" } }),6 });7}
uiEn holds the same keys as uiFr, each with its component's English default, so it changes nothing an English visitor saw before. An application whose fallbackLang is en, the default, does not need it. For any other language, copy uiFr as a starting point.
#Nav labels: name a key, don't call tr()
A page's nav is a class field, evaluated once when the router is constructed - outside React, where tr() does not exist and where the active language is whatever it happened to be at startup. Writing the label as a tr() call there freezes it; that is how the admin sidebar stayed English inside an otherwise French back office.
So a shell page names the key instead, and the sidebar, breadcrumbs and command palette resolve it at render time:
1products = $pageAdmin({ 2 path: "/products", 3 nav: { 4 label: "Catalogue", 5 labelKey: "shop.nav.products", 6 group: "Commerce", 7 groupKey: "shop.nav.group.commerce", 8 order: 100, 9 },10 lazy: () => import("./AdminProducts.tsx"),11});
label stays the English text and becomes the default passed to tr(), so a page whose key nobody translated renders exactly what it rendered before - never a raw key. group is untouched by the translation: it is the grouping key, and two pages are in the same section when they agree on it, in every language. Only groupKey decides what the heading says.
labelKey and groupKey are @alepha/ui's own additions to $page's nav, available through $pageNav and $pageAdmin, and on $settingsSection too. The framework's router never reads them.
#Lazy Loading
Only the current language and the fallback language (default: "en") are loaded on startup. When the user switches languages, the new language's dictionaries are loaded on demand.
On the server, all languages are loaded at startup for SSR.
#useI18n Hook
1import { useI18n } from "alepha/react/i18n";
The hook accepts two type parameters for full type safety: the class containing the dictionaries and one of its dictionary keys (to infer available translation keys).
1const Header = () => { 2 const { tr, l, setLang, lang, languages } = useI18n<App, "en">(); 3 4 return ( 5 <div> 6 <h1>{tr("hello")}</h1> 7 <p>Current: {lang}</p> 8 <select value={lang} onChange={(e) => setLang(e.target.value)}> 9 {languages.map((l) => (10 <option key={l} value={l}>{l}</option>11 ))}12 </select>13 </div>14 );15}
#tr(key, options?)
Translate a key. Returns the translated string, or the key itself if not found.
1tr("hello"); 2// "Hello" 3 4tr("welcome", { args: ["Alice"] }); 5// "Welcome, Alice" 6 7tr("greeting", { args: { name: "Alice", last4: 4242 } }); 8// "Hello Alice, your card ends in 4242" 9 10tr("ticket.status", { select: "open" });11// "Open"12 13tr("missing_key", { default: "Fallback text" });14// "Fallback text"
Options:
| Option | Type | Description |
|---|---|---|
args |
(string | number)[] or a record |
Positional arguments for $1, $2, or named ones for {name}. |
count |
number |
Selects a plural variant and fills {count} (see Plurals below). |
select |
string |
Selects the variant of that name (see Select below). |
default |
DictionaryEntry |
Fallback if the key is not found: a string or a variant object. |
Fallback behavior: if the key is not found in the current language, the fallback language ("en" by default) is checked. If still not found, the raw key string is returned.
#Plurals
A catalog value can be a variant object instead of a string, keyed by the plural categories of Intl.PluralRules (zero, one, two, few, many, other). other is required: a variant object without it does not compile.
1// en.ts 2export default { 3 "tickets.count": { one: "{count} ticket", other: "{count} tickets" }, 4}; 5 6// pl.ts 7export default { 8 "tickets.count": { 9 one: "{count} zgłoszenie",10 few: "{count} zgłoszenia",11 many: "{count} zgłoszeń",12 other: "{count} zgłoszenia",13 },14};
1tr("tickets.count", { count: 1 }); // "1 ticket"2tr("tickets.count", { count: 1234 }); // "1,234 tickets"
countpicks the variant, throughIntl.PluralRulesof the language the entry is written in. An English entry reached through the fallback on a Polish page is selected with English rules, since it is English text.{count}is the count formatted for that language withIntl.NumberFormat(1,234in English,1 234in French).$1,$2keep working inside a variant.- A category the entry lacks renders
other, and so does a variant entry read without acount. A language with no plural distinction writes{ other: "..." }alone. - A plain string entry is unchanged, and fills
{count}when it is given one. - There are no exact-number variants: a zero case that needs its own sentence is its own key.
A default can carry a variant object too. It belongs to no dictionary, so it is selected with the rules of the fallback language:
1tr("files.deleted", {2 count,3 default: { one: "{count} file deleted", other: "{count} files deleted" },4});
#Named arguments
A {name} placeholder is filled from a record passed as args; values are strings or numbers, inserted as written. Positional $1, $2 keep working, and an array never fills a name.
1// en.ts2export default {3 greeting: "Hello {name}, your card ends in {last4}",4};5 6tr("greeting", { args: { name: "Alice", last4: 4242 } });
{count}is thecountoption's: a named argument calledcountdoes not fill it.- A placeholder with no argument is left as written, and a substituted value is never read again: a value containing
{name},$2or<b>is inserted literally. - A literal brace is written doubled:
{{renders{and}}renders}, so"Write {{name}}"rendersWrite {name}.
Braces are syntax since named arguments: a catalog written before them that holds a literal {word} keeps rendering it only while no argument has that name, and should double its braces.
Names are type-checked when the catalog is written as const: a missing or misspelled name is then a compile error at tr(), across every variant of the entry. Any other catalog types its values string and accepts any record, and alepha i18n check reports a call that omits a name.
#Select
A variant object can also be chosen by a string, with the select option. other is what a value with no variant of its own renders:
1// en.ts2export default {3 "ticket.status": { open: "Open", closed: "Closed", other: "Unknown" },4};5 6tr("ticket.status", { select: ticket.status });
A call takes one selector: count and select together are a type error. A variant name carries no dot.
To type a catalog file, use DictionaryEntry:
1import type { DictionaryEntry } from "alepha/react/i18n";2 3export default {4 "tickets.count": { one: "{count} ticket", other: "{count} tickets" },5} satisfies Record<string, DictionaryEntry>;
#l(value, options?)
Localize a value (date, number, or error) according to the current locale. It always returns a string, like tr(), so its result goes straight into a string-typed field or a TSX attribute with no String() around it.
Number formatting:
1l(1234.56);2// "1,234.56" (en) / "1 234,56" (fr)3 4l(1234.56, { number: { style: "currency", currency: "USD" } });5// "$1,234.56"6 7l(0.85, { number: { style: "percent" } });8// "85%"
Uses Intl.NumberFormat under the hood. The number option accepts standard Intl.NumberFormatOptions.
Date formatting:
1l(new Date()); 2// "2/7/2026" (en) / "07/02/2026" (fr) 3 4l(new Date(), { date: "LLL" }); 5// "February 7, 2026 10:30 AM" (dayjs format string) 6 7l(new Date(), { date: "fromNow" }); 8// "2 hours ago" 9 10l(new Date(), { date: { year: "numeric", month: "long", day: "numeric" } });11// "February 7, 2026" (Intl.DateTimeFormatOptions)12 13l(new Date(), { date: "LLL", timezone: "America/New_York" });14// Formatted in Eastern time
The date option accepts:
- A dayjs format string (e.g.,
"LLL","YYYY-MM-DD","dddd, MMMM D YYYY") "fromNow"for relative timeIntl.DateTimeFormatOptionsfor native formatting
The timezone option accepts IANA timezone names.
Validation error localization:
SchemaValidationError is the schema-validation error Alepha throws:
1l(validationError);2// Localized validation error message
#setLang(lang)
Switch the current language. On the browser, this:
- Loads the new language's dictionaries if not already loaded
- Sets a
langcookie (persists for 1 year) - Updates the store, causing all
useI18nconsumers to re-render
The last call wins: when two switches overlap, the language asked for last is the
one that lands, whichever dictionary finishes loading last. A switch whose
dictionary fails to load rejects and changes nothing. The page's <title>
and meta tags are filled again in the new language, with the page's own head still
over the global one.
1setLang("fr");
#lang
The current language code string.
#languages
Array of all available language codes, derived from registered dictionaries.
#dir
The writing direction of the current language: "rtl" for a right-to-left language, "ltr" otherwise.
1const { dir } = useI18n();
The right-to-left languages are a fixed list (ar, he, fa, ur, ps, sd, ug, yi, dv, ckb), matched on the base language of the tag, so ar-EG is right-to-left. Anything else, a string that is not a language tag included, is "ltr".
<html dir> follows it, next to <html lang>: on the server for each request's language, and in the browser on a language switch. That is what makes Tailwind's rtl: variants match. An application that sets htmlAttributes.dir in its own $head keeps its value.
#Right-to-left in @alepha/ui
The kit's components mirror on a right-to-left page with nothing to configure:
- Spacing and placement are logical. The components use
ms-*,pe-*,start-*,end-*,text-start,border-sandrounded-e-*rather than their left and right forms, so a margin, an icon inside a field or a rounded corner lands on the side the text starts or ends. Write your own classes the same way. The few places where a side is physical on purpose (centring withleft-1/2, the device safe areaspl-safe/pr-safe, a time axis) say so in a comment. - Directional icons flip. A chevron that opens a submenu, a back arrow or a pagination arrow carries
rtl:-scale-x-100. An icon that names an action rather than a direction does not. - Base UI gets the direction. Popups placed on
side="inline-start"orside="inline-end", submenus and context menus included, and keyboard navigation in menus, sliders and tabs, read it from Base UI's direction provider, not from the document. A non-embeddedAppShellmountsDirectionProviderfromuseI18n().dir. An application with its own layout mounts it once, around everything:
1import { DirectionProvider } from "@alepha/ui";2 3<DirectionProvider>4 <Layout />5</DirectionProvider>;
Sidebar,SheetandPaneRailtakeside="start" | "end", which follows the direction, beside the physicalleftandright. ASheetwith nosideopens at theend.- The kit's own arrow keys follow it: in a segmented control, a table's tabs and a tree, Left and Right swap on a right-to-left page.
- The calendar and the toaster follow it too: the calendar swaps its previous and next buttons and its arrow keys, and toasts move to the bottom-left corner.
#Translate Component
<Translate> (also exported as <Tr>) is tr() as JSX:
1import { Tr } from "alepha/react/i18n";2 3<Tr k="welcome" args={["Alice"]} fallback="Welcome, $1" />;4<Tr k="tickets.count" count={3} />;
It takes the same args (positional or named), count and select as tr(), and its fallback can be a variant object.
#Localize Component
A component wrapper around l() for inline use in JSX:
1import { Localize } from "alepha/react/i18n";2 3<Localize value={new Date()} date="LLL" />4<Localize value={1234.56} number={{ style: "currency", currency: "EUR" }} />5<Localize value={new Date()} date="fromNow" timezone="Europe/Paris" />
Props:
| Prop | Type | Description |
|---|---|---|
value |
string | number | Date | DateTime | SchemaValidationError |
The value to localize. |
number |
Intl.NumberFormatOptions |
Number formatting options. |
date |
string | Intl.DateTimeFormatOptions |
Date formatting options. |
timezone |
string |
IANA timezone name. |
#SSR Language Detection
On the server, the language is resolved on each request via a server hook, so SSR renders use the correct language. The priority is:
With locale-prefix routing on (see below), the language in the URL (/fr/about)
wins over everything else. Otherwise:
- The
langcookie value (set bysetLang) - a manually-selected language always wins. - The
Accept-Languagerequest header - used only for first-time visitors (no cookie). The whole list is read, by descendingqthen in the order sent, and the first entry naming a registered language wins: withenandfrregistered,de-CH,fr-CH;q=0.9,en;q=0.8givesfr. An entry matches an exact registration first, then is cut one subtag at a time (zh-Hant-TW,zh-Hant,zh). Case is ignored. - The configured fallback language (
"en"by default).
The result is always a registered language, or the fallback. The cookie, the
header and the URL are the visitor's to write, so a value that names no
registered language is ignored: a lang cookie of en_US, or of a language the
app has no dictionary for, counts as no cookie, on the server and when the
browser boots. An app with no dictionary at all therefore always resolves a
request to fallbackLang.
A language is declared by a dictionary, and by nothing else. One you use only
for its direction (<html dir="rtl">) and its date and number formats, with no
translation yet, still needs one, which can be empty: every key then falls back
to the fallback language.
1class AppI18n {2 en = $dictionary({ lazy: () => import("./translations/en.ts") });3 // Declared with no string of its own: Arabic direction and formats,4 // English text.5 ar = $dictionary({ lazy: async () => ({ default: {} }) });6}
Because the cookie takes precedence, autodetection never overrides a choice the
user made explicitly. To always start in the fallback language regardless of the
browser's preferred language, disable it with autoDetect (see below).
#Configuration
The fallback language defaults to "en". It can be changed on the
I18nProvider:
1const i18n = alepha.inject(I18nProvider);2i18n.options.fallbackLang = "es";
Accept-Language autodetection is on by default. Disable it to always start in
the fallback language for first-time visitors:
1i18n.options.autoDetect = false;
If no dictionary is registered for fallbackLang, the first registered
language is used as the fallback instead.
#Locale-prefix routing (SEO)
By default the active language lives in a cookie and the URL is the same for
every language. That is invisible to search-engine crawlers - Googlebot does not
vary Accept-Language or keep cookies, so it only ever sees one language and
cannot index the others.
For multilingual SEO, enable prefix routing, which gives every non-default language its own crawlable URL:
1const i18n = alepha.inject(I18nProvider);2i18n.options.routing = "prefix";
/about → en (default language, unprefixed)
/fr/about → fr
/de/about → de
The default language (fallbackLang) stays unprefixed; every other registered
language gets a /<lang> path prefix. With prefix routing on:
The URL is the source of truth for language.
/fr/aboutalways renders in French, regardless of cookie orAccept-Language. This is what makes each language a stable, shareable, indexable URL.Every generated link carries the active prefix automatically:
router.path,router.push, and<Link>all stay within the current language. No app code changes are needed.setLang(code)navigates to the same page under the new prefix (instead of writing a cookie), so the language switcher just works.hreflangalternates are emitted in the SSR<head>for every language (plusx-default→ the unprefixed URL), telling crawlers the pages are translations of one another:html1<link rel="alternate" hreflang="en" href="https://site.com/about" />2<link rel="alternate" hreflang="fr" href="https://site.com/fr/about" />3<link rel="alternate" hreflang="x-default" href="https://site.com/about" />The origin is
PUBLIC_URLwhen it is set, and the request's own otherwise. Set it in production: the request's origin is itsHostheader, which the client chooses.There is no automatic redirect. An unprefixed path (
/about) is the default language by definition - visiting it never bounces a French browser to/fr. Google's guidance discourages auto-redirecting by perceived language, and it would hide content from crawlers. Use a soft "View in Français?" banner if you want to nudge first-time visitors.
Subtrees with nothing to crawl (a back office behind a sign-in) can stay
unprefixed with routingExclude, matched on a segment boundary. Inside them the
language is carried by the cookie, as with the default routing:
1i18n.options.routingExclude = ["/admin"];
Prefix routing requires the router module (alepha/react/router). Apps that are
fully behind authentication (not indexed) generally do not need it - the
cookie-based default is simpler there.