Skip to content

Locale and Translation ​

Moost does not ship an i18n runtime. Your app brings its translations — a plain map, or any library (i18next, FormatJS, …) — and registers them once with setTranslator(). Moost then:

  • picks the locale of each request from Accept-Language (or your own policy) — useLocale() / @Locale();
  • translates error responses — HttpError bodies and validation envelopes — in the request's locale;
  • gives your code and the packages built on moost one translate function — useTranslate().

With no translator registered, nothing changes: responses stay as authored, with no Vary header.

Setup in one call ​

A plain map, { [locale]: { [id]: template } }:

ts
import { setTranslator } from 'moost'

setTranslator({
  en: {},
  de: {
    NAME_TAKEN: 'Der Name {name} ist vergeben',
    'Order not found': 'Bestellung nicht gefunden',
  },
})

The locales are the map's keys. Templates use {name} placeholders, filled from the message's params. An id the map has no entry for keeps its English text.

Put the source language first

The first locale is the default: requests with no Accept-Language, or none the app has, get it. Always list the language your code is written in first — { en: {}, de: {…} }, even with no entries. A map with only translations, setTranslator({ de: {…} }), makes every such request German, Accept-Language: en included.

Or any library, as a function — return the final text, or undefined when there is no translation. List the locales the app serves in opts.locales, the default first. Without them requests get no locale, so nothing is translated, unless your own resolveLocale (or useLocale().set()) sets one:

ts
import i18next from 'i18next'
import { setTranslator } from 'moost'

await i18next.init({
  resources: { de: { translation: { NAME_TAKEN: 'Der Name {{name}} ist vergeben' } } },
  keySeparator: false, // ids are codes or English sentences: '.' is not a path
  nsSeparator: false, // ... and ':' is not a namespace
  interpolation: { escapeValue: false }, // JSON responses, not HTML
})

setTranslator(
  (id, params, { locale }) =>
    locale && i18next.exists(id, { lng: locale })
      ? i18next.t(id, { ...params, lng: locale })
      : undefined,
  { locales: ['en', 'de'] },
)

i18next options

Without keySeparator: false and nsSeparator: false, a source text such as 'Use: name.first' is read as a namespace and a key path and never found. Without escapeValue: false, params come back HTML-escaped (O'Brien).

setTranslator() is process-wide. Each call replaces the previous translator and starts over: everything derived from the old one (served message templates, see below) is recomputed. Load your languages before the server listens, or call setTranslator() again once a language has loaded. setTranslator(undefined) removes it.

If the translator throws, the English text is used and the error is logged once.

The locale of a request ​

MoostHttp picks each request's locale for you: Accept-Language negotiated against the translator's locales, the first locale when the header is missing or matches none. With more than one locale the response gets Vary: Accept-Language. The locales are read per request, so registering the translator after creating MoostHttp is fine.

For another policy — a ?lang query, a cookie, the user's profile — pass resolveLocale; it replaces the default. It runs lazily, on the first read in a request:

ts
import { getTranslatorLocales } from 'moost'
import { MoostHttp, useAcceptLanguage } from '@moostjs/event-http'
import { useCookies } from '@wooksjs/event-http'

const http = new MoostHttp({
  resolveLocale: () => {
    const locales = getTranslatorLocales()
    const fromCookie = useCookies().getCookie('lang')
    if (fromCookie && locales.includes(fromCookie)) return fromCookie
    return useAcceptLanguage().negotiate(locales, locales[0]) // adds Vary: Accept-Language
  },
})

A workflow started from the request, and an in-process fetch() made while serving it, read the request's locale. Other event kinds (CLI, WebSocket) have no default: set it with useLocale().set(locale).

Read the locale anywhere with useLocale(), or inject it with @Locale():

ts
import { Locale, useLocale } from 'moost'

useLocale().get() // 'de' | undefined
useLocale().set('de') // for this event and the events it starts

@Get('greeting')
greeting(@Locale() locale: string | undefined) {
  return locale === 'de' ? 'Hallo' : 'Hello'
}

Translating in your code ​

useTranslate() returns t(id, params?, fallback?) bound to the current event's locale:

ts
import { useTranslate } from 'moost'
import { HttpError } from '@moostjs/event-http'

const t = useTranslate()
t('Order not found') // 'Bestellung nicht gefunden' for a German request
t('Hello, {name}', { name: 'Ann' }) // 'Hello, Ann' where there is no translation

The id is a stable code (NAME_TAKEN, UPPER_SNAKE) when the message has one, else the English source text itself. Codes are one namespace across your app and the packages you use.

t returns, in this order:

  1. the translator's text — final, params are not filled in again;
  2. else fallback, as is — it is never filled, so pass text you already built, such as an error's English message;
  3. else the English template registered for the code (see below), or the id itself, with {name} placeholders filled from params.

So for a coded message, either pass the finished English text as fallback, or register its template with registerMessages() and pass no fallback — not a template as fallback.

Params are filled in one pass: a value that itself contains {x} is never expanded. formatMessage(template, params) is that fill, exported for your own use.

Error responses ​

You don't need to translate errors yourself. MoostHttp translates every error body before it is sent, in the request's locale:

ts
throw new HttpError(409, {
  message: `The name ${name} is taken`, // English: sent where there is no translation
  code: 'NAME_TAKEN',
  params: { name },
})
// German request → { "message": "Der Name Ann ist vergeben", "code": "NAME_TAKEN", ... }
  • A body with a code is translated by its code, the English message being the fallback.
  • A body without a code is translated by its message text.
  • Each entry of errors (validation envelopes: { path, message, code?, params?, custom? }, and the details of an entry) is translated by its code — by its message text when it has none or is custom (the app's own message). The top message that repeats the first entry ('name: Must not be empty') follows that entry's translation.

Wording per field ​

For an error entry the translator also gets the entry's path and code (a coded body's top message gets its code), and custom: true when the entry carries the app's own message (then id is that message). Use them when one message reads differently per field — the same REQUIRED code, say, as "Pick a product" for one field and the generic text elsewhere:

ts
setTranslator(
  (id, params, { locale, path, code, custom }) => {
    if (locale !== 'de') return undefined
    // `custom`: the app wrote its own message for this field — keep it (or translate it by text)
    if (!custom && code === 'REQUIRED' && path === 'items.0.productId') {
      return 'Wählen Sie ein Produkt'
    }
    const text = de[id]
    return text === undefined ? undefined : formatMessage(text, params)
  },
  { locales: ['en', 'de'] },
)

path, code and custom are set only while an error body is translated, which is never cached. useTranslate() and the message templates don't get them.

The top message that repeats the first entry keeps the path: prefix after translation ('name: Darf nicht leer sein'). Pass pathPrefix: false to send just the entry's translated text ('Darf nicht leer sein'). The prefix is dropped even when the entry has no translation: the top message is then the entry's English text. Requests without a locale are left as they are:

ts
setTranslator(translations, { pathPrefix: false })

Both require moost 0.7.5 or later.

Your own transformErrorBody still runs after it, with the translated body (or the untranslated one if translating failed). A WooksHttp you create yourself and pass to MoostHttp is used as is: give it a resolveLocale (as above) and call translateErrorBody(body, ctx) from its transformErrorBody.

Clients branch on code, never on text

message changes with the locale. Keep client logic on code (and params), and show message to the user.

Message templates for clients ​

Packages that produce coded messages (validators, forms, workflows) register their English templates once, with registerMessages(). You can register your own the same way:

ts
import { registerMessages } from 'moost'

registerMessages({
  NAME_TAKEN: 'The name {name} is taken',
  TOO_MANY_ITEMS: 'At most {max} items',
})

A registered code needs no English fallback at the call site: t('NAME_TAKEN', { name }) fills the template when there is no translation.

Clients that validate or render forms themselves need the templates in the user's language. useTranslation() returns them for the current request — or undefined when no translator is registered or the request has no locale:

ts
import { useTranslation } from 'moost'

@Get('messages')
messages() {
  const translation = useTranslation()
  return translation ? translation.messages() : {}
  // { NAME_TAKEN: 'Der Name {name} ist vergeben', TOO_MANY_ITEMS: 'Höchstens {max} Elemente' }
}

messages() holds only the codes whose translation differs from English, with their {name} placeholders kept — the client fills them in. The result is cached per translator, locale and scope. translation.key names that combination (undefined for a locale outside the translator's locales — don't cache then): use it to cache anything else you derive from the translation. It changes with every setTranslator() call and every registerMessages() call that adds or changes a template. Keep one cache entry per translation.partition (the locale, plus the scope when there is one) and replace it when the key changes:

ts
import type { TTranslation } from 'moost'

const cache = new Map<string, { key: string; value: Summary }>()

function localizedSummary(translation: TTranslation): Summary {
  const { key, partition } = translation
  if (key === undefined) return buildSummary(translation)
  const hit = cache.get(partition)
  if (hit?.key === key) return hit.value
  const value = buildSummary(translation)
  cache.set(partition, { key, value })
  return value
}

Such a cache holds one entry per locale and cached scope. If your scopes change across setTranslator() calls, clear it when you call setTranslator() again.

Plurals and number formats in served templates

Templates are made by calling your translator with each param set to its own placeholder ({ max: '{max}' }), so plural forms can't be chosen and number formatters (ICU #, {count, number}) break. In translations of registered codes, write plain placeholders ({count} in a map, {{count}} in i18next).

Per-tenant wording ​

Translations are cached per locale. When the wording also differs per tenant, brand or user group, give setTranslator() a scope: a function that runs in the request's context and names the wording to use — or returns undefined for the shared wording, cached per locale exactly as without the option. The translator gets it as scope:

ts
import { formatMessage, setTranslator } from 'moost'
import type { TTranslations } from 'moost'

const shared: TTranslations = { en: {}, de: { ORDER: 'Bestellung' } }
const perTenant: Record<string, TTranslations> = { acme: { de: { ORDER: 'Auftrag' } } }

setTranslator(
  (id, params, { locale, scope }) => {
    if (!locale) return undefined
    const text = (scope ? perTenant[scope]?.[locale]?.[id] : undefined) ?? shared[locale]?.[id]
    return text === undefined ? undefined : formatMessage(text, params)
  },
  // your own composable: the authenticated principal's tenant, undefined for unknown ones
  { locales: ['en', 'de'], scope: () => useTenantId() },
)
  • Keep the translator pure per (locale, scope). It must return the same text for the same id, params, locale and scope: translated templates, and what packages built on moost serve from them, are cached under that combination.
  • Derive scope from a validated value — the authenticated principal's tenant, say — and return undefined for unknown tenants. Never pass request input (a header, a query param) straight through.
  • Keep scope cheap. It is called each time a translation is taken; read a value the request has already resolved. A string or a finite number names a scope; anything else is the shared wording.
  • Up to 32 scopes are cached. The slots go to the first 32 distinct scopes seen since the last setTranslator() (or registerMessages() that changed a template) and are held until the next one; further scopes are still translated with their scope, but per request. Scopes taken from untrusted input could use up the slots and turn caching off for real tenants.
  • If scope throws, the request gets the shared wording, uncached, and the error is logged once.

Requires moost 0.7.4 or later. Translated /meta of atscript-db (≥ 0.1.172) and workflow form schemas of atscript-ui (≥ 0.1.168) cache per scope too. With earlier versions of those packages each request still gets its scope's wording, but their caches keep one scope per locale at a time.

See also ​

Released under the MIT License.