jsails/i18n is a dependency-free message layer over nested string maps. The
browser-safe translator is MessageTranslator; the server-only half adds catalog
loading, a plugin, and a global I18n facade.
new MessageTranslator({ messages, locale?, fallbackLocale?, onMissing? })
returns a Translator with:
t(key, options?)resolves a dot-path key (nav.home) against the active locale's map, then the fallback locale's, and interpolates{name}(plus Laravel-style:name/:Name/:NAMEcase variants).optionsmay carry ascope(string or array of dot segments, folded onto the key) and an ordereddefault(a literal, another{ key }, or an array tried left-to-right).t(keys[])resolves a batch in order. Returns the key itself when missing.tChoice(key, count, options?)selects a plural form with the built-inIntl.PluralRulesfor the locale — a plural key maps to an object keyed by category (one,few,many,other, ...), never a bespoke index.exists(key, options?)reports whether a key resolves (no default applied).localize(value, options?)/l(value, options?)format a date, time, datetime, number, currency, or percent throughIntl(currency requires an ISO 4217currencycode). This is an addition Laravel does not have.locale()/fallbackLocale()/withLocale(next)read the active/fallback locales or derive a translator with a new locale.
The translator holds the passed messages reference and never mutates it.
locale and fallbackLocale are validated eagerly; a malformed locale throws a
value-free I18nError. Errors never echo a locale string.
import { MessageTranslator } from 'jsails/i18n';
const translator = new MessageTranslator({ messages, locale: 'en', fallbackLocale: 'en' });
translator.t('nav.home');
translator.t('short', { scope: 'date.formats' }); // resolves `date.formats.short`
translator.tChoice('cart.items', 3);
translator.localize(new Date(), { dateStyle: 'long' }); // "March 14, 2023"
Catalogs, the plugin, and the global I18n
An app configures i18n in jsails.app.js and reads translations through the
ambient I18n global:
// jsails.app.js
export default {
i18n: { locale: 'en', fallbackLocale: 'en', loadPaths: ['lang'] },
};
// any page or API (inside a request)
I18n.t('nav.home'); // per-request locale, ambient scope
I18n.l(new Date(), { dateStyle: 'long' });
The i18n block builds the i18n plugin, which loads every catalog at startup,
resolves each request's locale, and publishes the I18n facade. The keys:
| Key | Default | Meaning |
|---|---|---|
locale |
'en' |
The locale served when a request does not select one. |
fallbackLocale |
'en' |
Where a key missing from the served locale is looked up. |
loadPaths |
none | Catalog directories, relative to the project root. |
catalogs |
none | In-memory catalogs (tests, demos), keyed by locale. |
locales |
none | Locales served under a URL prefix (/fr/about). |
defaultLocale |
none | The un-prefixed locale; in locales, equals locale. |
loadPaths and catalogs are mutually exclusive. I18n.t, I18n.tChoice,
I18n.exists, I18n.l, I18n.locale(), and I18n.availableLocales() follow
the translator methods above. For code that prefers imports,
jsails/i18n/server exports I18n and the bare helpers t, l, and
choice. Outside a request the facade serves the default locale.
Catalog files
Each load path holds catalogs in either of two layouts, and both may be mixed:
lang/
en.json flat: one nested object for the locale
fr.json
en/
nav.json grouped: the file stem becomes the top-level key (nav.*)
validation.json
For each locale the loader reads the flat files first, then the group
directories, path by path in loadPaths order, and deep-merges them; a later
source wins a key conflict. Every catalog file is parsed as JSON (only .json
files are read by default); a module catalog is never imported. A missing
directory or file is skipped. A catalog that cannot be read, is not valid JSON,
or is not a message object fails startup with an I18nError (io_failed,
unparseable, invalid_messages) that names the catalog, never its content.
Loaders
jsails/i18n/loader is the server-only half of catalog loading, for tests and
for tools that read catalogs outside the plugin. It reads node:fs, so never
import it into a client bundle; the browser-safe jsails/i18n entry does not
re-export it.
import { createArrayLoader, createFileLoader, mergeCatalogMaps } from 'jsails/i18n/loader';
const files = createFileLoader({ loadPaths: ['lang'] });
const en = await files.load('en'); // merged messages, or undefined
await files.availableLocales(); // ['en', 'fr']
const memory = createArrayLoader({ en: { nav: { home: 'Home' } } });
const merged = mergeCatalogMaps(en ?? {}, { nav: { home: 'Start' } }); // overlay wins
A Loader has load(locale), availableLocales(), and reload().
createFileLoader also takes extensions (default ['.json']).
Locale resolution
Each request gets one locale, made ambient for everything it awaits and exposed
as context.locale on the request context; I18n.locale() reports it. A job
dispatched during the request runs in the same locale: the locale travels in
the job's context carrier (see
Observability).
Without locales, every request is served in the default locale.
Translators are cached per served locale, so request input can never grow the
cache.
Set locales to serve locale-prefixed URLs:
// jsails.app.js
export default {
i18n: {
locale: 'en',
fallbackLocale: 'en',
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
loadPaths: ['lang'],
},
};
- Every page and API route is also registered under
/{locale}/<route>for each locale inlocalesexceptdefaultLocale, so/fr/aboutand/de/aboutrenderpages/about, and/fr/api/postsservesapi/posts. Route params are the same as on the bare route. - The bare route (
/about) always stays registered, and the default locale gets no prefix:/en/aboutis a 404. WhendefaultLocaleis not set, no locale is exempt, so every entry inlocalesgets a prefix (/en/aboutincluded) next to the bare route. - When the first path segment exactly matches an entry in
locales, that locale becomes the request locale. The match is case-sensitive and covers the whole segment, so/FR/aboutand/french/aboutare not prefixes.I18nthen translates in the closest locale your catalogs serve (withlocaleandfallbackLocalealso counted), so a prefix that has no catalog is served inlocale. - A request without a prefix is served in the default
locale. The config does not readAccept-Languageor a cookie. - Each entry in
localesmust be a valid, unique locale tag, and the list must not be empty.defaultLocalemust be one oflocalesand equallocale, because unprefixed URLs are always served inlocale. A bad value fails startup with anAppConfigErrorthat never echoes the value. - Prefixes apply to the served app. A static export (
jsails build) writes the bare routes only.
Localized links and hreflang
localizedPath(route, locale, defaultLocale?) from jsails/i18n builds the
prefixed URL for a route: localizedPath('/about', 'fr', 'en') is
/fr/about, and the default locale stays un-prefixed. hreflang(route, { locales, defaultLocale, origin }) returns one { locale, href } per locale
with absolute hrefs, for the alternates field of
page metadata:
// pages/about.tsx
import { hreflang } from 'jsails/i18n';
import { defineMetadata } from 'jsails/seo';
const links = hreflang('/about', {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
origin: 'https://example.com',
});
export const metadata = defineMetadata({
title: 'About',
alternates: [
...links.map((link) => ({ hreflang: link.locale, href: link.href })),
{ hreflang: 'x-default', href: 'https://example.com/about' },
],
});
hreflangRel(locale, defaultLocale) returns x-default for the default locale
and the locale itself otherwise, for apps that emit the default only as
x-default. All three helpers are pure and browser-safe.
Finding missing keys
jsails i18n:missing scans the compiled page and API modules for translation
calls and reports every key that no catalog defines, with the file and line of
each use. It exits 1 when a key is missing, so it can gate CI.
jsails i18n:missing [--config jsails.app.js] [--json] [--unused]
- It recognizes
I18n.t,I18n.tChoice, andI18n.exists, and the baretandchoiceonly when they are imported fromjsails/i18n/server(so a test runner'stis never mistaken for one). A literalscopeoption is folded into the key. - A key that is not a string literal (
t(someKey)) cannot be checked; such calls are counted and reported asdynamic, never guessed. --unusedalso lists catalog keys no code uses.--jsonprints a machine report.- The report names keys and locations only, never translation text.
See CLI for the full command list.
Safety notes
- Interpolation is a single pass: a substituted value is never re-scanned,
so a user-supplied
{name}or:nameinside a parameter is printed as-is, and only the parameter's own properties are read. Translations are plain strings; rendering them through Preact escapes them like any other text. - Locale values from requests are validated and negotiated before they reach
Intl, and errors never echo a locale string. l()reuses oneIntlformatter per locale and option set.
Next steps
- Theme Tokens — the shared CSS token contract.
- Feature Flags — boolean gates and A/B scopes.
- Services & Utilities — the cluster of small focused services.