i18n
createI18n looks up messages by key in the active locale, falls back to another locale and then to the key itself, interpolates :name parameters, picks plural forms by count, and formats numbers and dates with Intl. Where the messages are written in your code, a key that does not exist is a type error. negotiateLocale says which of your locales a request asks for. Messages are plain objects, flat or nested; loadTranslations reads them from JSON files under Node.
Import
import { createI18n } from '@loewen-digital/fullstack/i18n'The entry has no code that needs Node, so a component imports it as well as the server does and a client build has nothing to warn about. What reads files lives in @loewen-digital/fullstack/i18n/node.
Basic usage
import { createI18n } from '@loewen-digital/fullstack/i18n'
const messages = {
en: {
welcome: 'Welcome, :name!',
items: 'no items|one item|:count items',
auth: { errors: { invalid: 'Invalid email or password.' } },
},
de: {
welcome: 'Willkommen, :name!',
items: 'keine Einträge|ein Eintrag|:count Einträge',
},
}
const i18n = createI18n({ locale: 'de', fallback: 'en', messages })
i18n.t('welcome', { name: 'Alice' }) // 'Willkommen, Alice!'
i18n.t('auth.errors.invalid') // 'Invalid email or password.' from the fallbackKeys use dot notation into nested objects; a flat key with dots in it ('auth.errors.invalid': '...') works as well, at the top of a catalog. A parameter that is not passed stays as :name in the output.
Keys that are checked
t and tn take only keys that have a text in one of the locales, as long as the names of the messages are known when the code is checked: an object in your source, as above, or an imported JSON file. A typo, or a key that was renamed in the catalog, is then an error in the editor and in tsc, not a notes.titel on the page.
// @ts-expect-error Argument of type '"welcom"' is not assignable to '"welcome" | "items" | "auth.errors.invalid"'
i18n.t('welcom')
// @ts-expect-error a group is no text
i18n.t('auth.errors')- Which keys: every key of every locale together. A text only the fallback has is a key, and so is one only
dehas. Whether each locale has all of them is whatmissingKeystells a test. - Catalogs loaded at runtime:
loadTranslationsand anything else typed asRecord<string, Record<string, unknown>>leavetopen to any string, as before. - A key put together at runtime: type the instance as the plain
I18nInstance, or ask for it withcreateI18n<Messages>(…). Both take any string. - The type itself:
MessageKey<Catalog>is the union of a catalog's keys, for a function of your own that passes keys on.
import type { I18nInstance, MessageKey } from '@loewen-digital/fullstack/i18n'
type Key = MessageKey<(typeof messages)[keyof typeof messages]> // 'welcome' | 'items' | 'auth.errors.invalid'
export function errorText(i18n: I18nInstance, code: string): string {
return i18n.t(`auth.errors.${code}`) // any string: the instance is the plain one
}
errorText(i18n, 'invalid')createStack passes the keys on: stack.i18n.t knows the messages its config names.
A key without a text
A key that has a text neither in the active locale nor in the fallback comes back as the key itself. onMissing is told each time, right before that, with the key and the active locale. Log it in production; throw in tests and in development, and what you throw leaves t.
const strict: I18nInstance = createI18n({
locale: 'de',
fallback: 'en',
messages,
onMissing(key, locale) {
throw new Error(`No text for "${key}" in ${locale} or the fallback.`)
},
})
strict.t('welcome', { name: 'Alice' }) // 'Willkommen, Alice!'
strict.t('auth.errors.invalid') // from the fallback: not missing
// strict.t('notes.titel') throwsA text that only the fallback has is not missing here. Without onMissing nothing changes: the key is the answer.
Catalogs that drift apart
missingKeys(messages) names every key that one locale has a text for and another one lacks. It is made for a test: the catalogs are complete when the list is empty, and a failing test prints what to translate.
import { missingKeys } from '@loewen-digital/fullstack/i18n'
missingKeys(messages) // [{ locale: 'de', key: 'auth.errors.invalid' }]// src/lib/i18n/catalogs.test.ts
import { expect, it } from 'vitest'
import { missingKeys } from '@loewen-digital/fullstack/i18n'
import { loadTranslations } from '@loewen-digital/fullstack/i18n/node'
it('has every text in every language', async () => {
expect(missingKeys(await loadTranslations('./locales'))).toEqual([])
})- It compares which keys exist, the way
tfinds them: a key written flat and the same key written nested are one. - It does not read the texts: one that is empty, or lacks a
:namethe other locale fills, is not found. - A locale that leaves texts to the fallback on purpose (
de-CHoverde) is filtered out by name:missingKeys(messages).filter((missing) => missing.locale !== 'de-CH').
Plural forms
tn(key, count, params?) splits the message at | and picks a form: two forms are one|other (count === 1 takes the first), three are zero|one|other. :count is replaced in the chosen form.
i18n.tn('items', 0) // 'keine Einträge'
i18n.tn('items', 1) // 'ein Eintrag'
i18n.tn('items', 7) // '7 Einträge'Locales
locale(name) switches the instance; getLocale() reads it. An instance is one active locale, so a server that serves several languages creates an instance per request (they are cheap: the messages object is shared by reference).
import { negotiateLocale } from '@loewen-digital/fullstack/i18n'
const locales = ['en', 'de'] as const
export function i18nFor(request: Request) {
const locale = negotiateLocale(request, locales) ?? 'en' // 'en' | 'de'
return createI18n({ locale, fallback: 'en', messages })
}The locale of a request
negotiateLocale(source, supported) reads an Accept-Language header and answers the locale of supported the request wants most, or undefined when it asks for none of them. source is the header or the Request that carries it; a missing header (null) is fine. The answer is typed as one of the locales you passed. It is plain string work: it runs on Workers, in Node and in the browser.
negotiateLocale('fr-CH, fr;q=0.9, de;q=0.8, en;q=0.7', ['en', 'de']) // 'de'
negotiateLocale('en;q=0.5, de;q=0.9', ['en', 'de']) // 'de': the weight counts, not the position
negotiateLocale('de-CH', ['en', 'de']) // 'de'
negotiateLocale('de', ['en-US', 'de-DE']) // 'de-DE'
negotiateLocale('fr, *;q=0.5', ['en', 'de']) // undefined| The header says | What counts |
|---|---|
Weights (;q=0.8) | The language with the higher weight comes first; among equal weights the order of the header decides |
q=0 | "Not this language": the entry is left out |
* | Names no language and is left out. What a request without a wish gets is your default |
A region you do not have (de-CH, you speak de) | The language: de. A locale that says exactly what was asked for comes first |
A language you only have with a region (de, you speak de-DE) | That locale; de-CH gets it as well, as the same language from elsewhere. Of several (en-GB, en-US) the one earlier in your list wins |
Upper or lower case (DE-de) | Does not matter. The answer is written the way your list writes it |
| An entry that is no language with an optional weight, or a tag of more than 35 characters | Skipped; the entries next to it still count |
The header is one source among several, and usually the last one asked: what the account chose, a cookie of the device or the address of the page say more about a reader than the browser's settings. Which of them wins is your app's decision, and so is the default.
type Locale = (typeof locales)[number]
const isLocale = (value: unknown): value is Locale => locales.some((locale) => locale === value)
export function localeOf(request: Request, account?: { locale?: string }, cookie?: string): Locale {
return [account?.locale, cookie].find(isLocale) ?? negotiateLocale(request, locales) ?? 'en'
}Numbers and dates
number and date are Intl.NumberFormat and Intl.DateTimeFormat for the active locale, with their options passed through. date takes a Date, a timestamp or a date string.
i18n.number(1234567.89) // '1.234.567,89'
i18n.number(0.42, { style: 'percent' }) // '42 %'
i18n.number(9.99, { style: 'currency', currency: 'EUR' }) // '9,99 €'
i18n.date(new Date(2026, 3, 5)) // '5.4.2026'
i18n.date('2026-04-05T15:45:00Z', { dateStyle: 'long' }) // '5. April 2026'
i18n.date(Date.now(), { timeStyle: 'short' })Loading messages from files
loadTranslations(directory) reads every <locale>.json in a directory into the messages shape: en.json becomes the catalog of en. It needs node:fs and has an entry of its own for that, apart from createI18n. The package root exports it as well.
import { createI18n } from '@loewen-digital/fullstack/i18n'
import { loadTranslations } from '@loewen-digital/fullstack/i18n/node'
async function fromFiles() {
const messages = await loadTranslations('./locales') // en.json, de.json, ...
return createI18n({ locale: 'en', messages })
}Config options
createI18n(config) reads these; every option has a default.
| Option | Type | Default | Description |
|---|---|---|---|
locale | string | 'en' | Active locale |
fallback | string | 'en' | Locale tried when a key is missing in the active one |
messages | Record<locale, messages> | {} | Message catalogs, flat or nested |
onMissing | (key, locale) => void | none | Called each time a key has no text in the active locale or the fallback |
There is no directory option: call loadTranslations yourself and pass what it answers as messages.