DocsNode
Node reference
Reference for @generic-translation/node - request-scoped locales, t(), dictionaries, runtime translation and Express, Fastify and Hono adapters.
On this page
- Install
- Quick start (Express)
- Configuration
- Where translations come from
- Caching
- Locale
- withLocale(locale, fn)
- getLocale()
- getRequestLocale(req, options?)
- withRequestLocale(req, fn, options?)
- Translating
- getGenericTranslation(locale?) → t
- msg(message, options?) and getMessages()
- getDictionary(locale?) → d
- Runtime translation
- Formatting
- Framework adapters
- Express / Connect — genericTranslationExpress(options?)
- Fastify — genericTranslationFastify
- Hono — genericTranslationHono(options?)
- Plain http
- Other exports
- Testing your app
Server-side internationalization for Node backends. Translate API responses, emails,
notifications and server-rendered HTML with Generic Translation —
in Express, Fastify, Hono, or a plain http server.
- Request-scoped locale through
AsyncLocalStorage: noreqthreading through your call stack. - ICU MessageFormat (plurals, selects, numbers, dates, tags), keyed by content hash — the source string is the key.
- Translations from a custom loader, local JSON files, or the Generic Translation CDN, cached in memory with stale-while-revalidate.
- Optional on-demand translation of strings that have not been translated yet.
- ESM + CJS + types. One runtime dependency (
@generic-translation/core, itself dependency-free). Node >= 20.
Install
@generic-translation/node is not published to npm yet. Clone the parent repository https://github.com/generic-translation/generic-translation, build packages/core and packages/node (pnpm install && pnpm build in each), and link them from your project:
{
"dependencies": {
"@generic-translation/core": "link:../generic-translation/packages/core",
"@generic-translation/node": "link:../generic-translation/packages/node"
}
}
The package depends on @generic-translation/core and requires Node 20 or newer.
Quick start (Express)
import express from "express";
import { initializeGenericTranslation, genericTranslationExpress, getGenericTranslation, formatCurrency } from "@generic-translation/node";
initializeGenericTranslation({
defaultLocale: "en",
locales: ["es", "fr", "ja"],
projectId: process.env.GENERIC_TRANSLATION_PROJECT_ID, // published translations come from the Generic Translation CDN
});
const app = express();
app.use(genericTranslationExpress());
app.get("/", (req, res) => {
res.send(req.t("Hello {name}, you have {count, plural, one {# message} other {# messages}}.", {
name: "Ada",
count: 3,
}));
});
// Anywhere deeper in the call stack — no request object needed:
async function orderSummary(total: number) {
const t = await getGenericTranslation();
return t("Your total is {total}", { total: formatCurrency(total, "EUR") });
}
app.listen(3000);
curl -H "Accept-Language: es" localhost:3000/
curl "localhost:3000/?locale=fr"
A runnable version lives in examples/express in the package repository.
Configuration
Call initializeGenericTranslation(options) once at startup, before handling requests. Calling it again
replaces the configuration and drops all caches.
| Option | Type | Default | Description |
|---|---|---|---|
defaultLocale |
string |
"en" |
Locale your source strings are written in. |
locales |
string[] |
[] |
Locales you serve. The default locale is always included. |
projectId |
string |
GENERIC_TRANSLATION_PROJECT_ID |
Generic Translation project. Enables the CDN source. |
apiKey |
string |
GENERIC_TRANSLATION_API_KEY |
Project API key. Only needed for runtime translation (translations:generate). |
baseUrl |
string |
GENERIC_TRANSLATION_API_URL, then the public API |
API / CDN origin. |
loadTranslations |
(locale) => Promise<Record<string, string>> |
— | Custom source. Highest priority. |
translationsDir |
string |
— | Directory containing [locale].json maps. |
dictionary |
object | string |
— | Nested dictionary, or a path to its JSON file. |
cacheTtlMs |
number |
60000 |
How long a loaded map stays fresh. Infinity never refreshes. |
runtimeTranslation |
boolean | "background" | "await" | { mode } |
false |
Translate missing strings on demand. |
fetch |
typeof fetch |
global fetch |
Custom fetch (proxies, tests). |
onError |
(error, info) => void |
console.warn |
Load / runtime-translation failures. info is { phase, locale, source? }. |
Keep apiKey on the server. Never expose it to a browser.
Where translations come from
A translation map is a flat JSON object, { "<hash>": "<translated ICU string>" }, the same
payload the Generic Translation CLI writes and the CDN serves. For each locale the sources are tried in
priority order, and the first one that yields a map wins:
loadTranslations(locale)— your own function (database, S3, bundled import, …).translationsDir— reads[dir]/[locale].json.- CDN —
GET {baseUrl}/cdn/{projectId}/{locale}.json, whenprojectIdis set. No API key involved.
A source that throws, returns null/undefined, or has no file for the locale falls through to
the next one. If every source fails, t() returns source text and the load is retried shortly
(at most 30 s later) instead of waiting out the full TTL. Loading never throws into your request.
Caching
- The first request for a locale loads its map; concurrent first requests share one load.
- Within
cacheTtlMs, the cached map is used with no I/O. - After the TTL, the stale map is served immediately and a single background refresh runs.
Already-created
tfunctions see the refreshed data. - If a refresh fails, the stale map is kept and the refresh is retried later.
- Nothing is loaded for the default locale.
preloadTranslations(locales?) warms the cache at startup; clearTranslationCache(locale?)
drops it (for example from a webhook handler for project.published).
Locale
withLocale(locale, fn)
Runs fn with locale bound to the async context and returns its result. Everything called
inside — including after await, timers and I/O — sees that locale. Concurrent calls are isolated
from each other. The locale is matched against your configured locales (fr-CA → fr); if
nothing matches, the default locale is bound.
await withLocale(user.locale, async () => {
const t = await getGenericTranslation();
await sendEmail(user.email, t("Your order has shipped"));
});
Useful for queue workers, cron jobs and anything else that has no HTTP request.
getLocale()
The locale bound to the current context, or the default locale outside any context.
Also: getLocales() (supported locales, default first) and getDefaultLocale().
getRequestLocale(req, options?)
Negotiates the locale for a request, in this order:
?locale=query parametergeneric-translation-localecookieAccept-Languageheader (by quality)- the default locale
Each candidate is matched against the configured locales; unsupported or malformed values are
skipped. req can be a Node IncomingMessage, a Fetch Request, an Express or Fastify request
(parsed req.query / req.cookies are used when present), or any { headers, url } object.
options is { queryParam?: string; cookieName?: string }.
withRequestLocale(req, fn, options?)
For servers without a middleware layer: negotiates the locale, loads its translations and runs
fn(t, locale) inside the locale context.
import { createServer } from "node:http";
import { withRequestLocale } from "@generic-translation/node";
createServer((req, res) =>
withRequestLocale(req, (t, locale) => {
res.setHeader("Content-Language", locale);
res.end(t("Hello!"));
}),
).listen(3000);
Translating
getGenericTranslation(locale?) → t
Async: resolves once the locale’s translations are loaded. locale defaults to the current one.
const t = await getGenericTranslation();
t("Welcome back!");
t("Hello {name}", { name });
t("{count, plural, =0 {No results} one {# result} other {# results}}", { count });
t("Save", { $context: "button label" }); // disambiguate for the translator
t("Close", { $context: "verb", $id: "modal.close" }); // optional stable id
t("Read the <0>docs</0>", { 0: (chunks) => `<a href="/docs">${chunks}</a>` });
- The first argument is an ICU message in your default locale. Its hash (source + context) is the lookup key, so there are no key files to maintain.
$contextis part of the hash;$idis not. Neither is passed to the formatter.- Tags are stripped to their inner text unless you pass a function for that tag.
- If a translation is missing or malformed, the source message is formatted instead. If the
source itself is not valid ICU, it is returned as-is.
t()never throws. t.localeis the locale it translates into.t.resolve(message, values)returns a promise; see runtime translation.
For the Generic Translation CLI to extract your strings, pass string literals to t(). The CLI recognises t() from getGenericTranslation(), msg(), req.t() / request.t() (from genericTranslationExpress / genericTranslationFastify, in files that import anything from @generic-translation/node), Hono’s c.get("t"), the t passed to withRequestLocale callbacks and dictionary entries; tx() is never extracted. See what gets extracted. You can also declare strings with msg() and submit getMessages() through the API client as shown below.
msg(message, options?) and getMessages()
Declare messages at module scope, where there is no request yet:
import { msg, getGenericTranslation } from "@generic-translation/node";
const SUBJECT = msg("Your invoice for {month}");
const CTA = msg("Pay now", { context: "email button", id: "invoice.cta" });
export async function invoiceEmail(month: string) {
const t = await getGenericTranslation();
return { subject: t(SUBJECT, { month }), button: t(CTA) };
}
msg() returns a frozen descriptor { source, context?, id?, hash, dataFormat } that t()
accepts in place of a string (its context travels with it). getMessages() returns everything
registered so far, de-duplicated by hash — handy for submitting strings for translation:
import { getMessages, getClient } from "@generic-translation/node";
await getClient().submitEntries({ entries: getMessages() });
getDictionary(locale?) → d
For teams that prefer keyed strings. The dictionary is nested JSON whose leaves are either a
message or [message, { context }]; ids are dot paths.
{
"nav": { "home": "Home", "orders": "Orders" },
"actions": { "save": ["Save", { "context": "button label" }] },
"cart": { "items": "{count, plural, one {# item} other {# items}}" }
}
initializeGenericTranslation({ defaultLocale: "en", locales: ["es"], dictionary: "./dictionary.json" });
const d = await getDictionary();
d("nav.home");
d("cart.items", { count: 2 });
d.has("nav.home"); // true
Entries are stored by hash like every other string, so the dictionary shares translations with
t() calls that use the same source text and context. An unknown id returns the id itself.
getDictionaryEntries() lists the flattened entries.
Runtime translation
Runtime translation asks the Generic Translation API to translate a string the moment it is first needed. It
needs projectId and an apiKey with the translations:generate permission.
initializeGenericTranslation({
defaultLocale: "en",
locales: ["es", "fr"],
projectId: process.env.GENERIC_TRANSLATION_PROJECT_ID,
apiKey: process.env.GENERIC_TRANSLATION_API_KEY,
runtimeTranslation: true, // or "background" | "await"
});
Two modes decide what happens when t() meets a string with no translation:
| Mode | Behaviour |
|---|---|
"background" (true) |
t() returns the source text immediately and starts a translation in the background. Later calls return the translation. Requests are never slowed down. |
"await" |
getGenericTranslation() / getDictionary() wait until every message registered with msg() and every dictionary entry is translated (batched, 50 per request). Inline t("...") literals still behave as in background mode. |
In either mode you can wait for a single string explicitly:
const t = await getGenericTranslation();
const text = await t.resolve("A brand new string {n}", { n: 1 });
Guarantees:
- Deduplicated — concurrent requests for the same string and locale share one API call.
- Cached — a translated string is kept in memory until
clearTranslationCache(). - Failure-tolerant — on an API error the source text is used and that string is not retried for 60 seconds.
- Nothing is sent for the default locale or for strings that already have a translation.
tx(text, options?)
Translates arbitrary text — user-generated content, database rows — regardless of the
runtimeTranslation setting.
const review = await tx(row.reviewText, { context: "product review" });
const forSpanish = await tx("Fresh bread daily", { locale: "es" });
options: locale (default: current), context, id, and dataFormat — "STRING" by default,
meaning the text is opaque and braces or apostrophes need no escaping. Resolves to the original
text when no translation is needed or the call fails.
Formatting
Thin wrappers over Intl, bound to the current locale (falling back to the default locale).
Pass locales in the options to override.
import { formatNum, formatCurrency, formatDateTime, formatRelativeTime, formatList } from "@generic-translation/node";
formatNum(1234567.891); // "1.234.567,891" in de
formatNum(0.42, { style: "percent" });
formatCurrency(1999.5, "EUR");
formatDateTime(new Date(), { dateStyle: "long" });
formatRelativeTime(-3, "day"); // "3 days ago"
formatList(["Ada", "Grace", "Linus"]); // "Ada, Grace, and Linus"
Framework adapters
None of the adapters import their framework; they are structurally typed, so @generic-translation/node adds
no framework dependency. All accept the same options:
{
locale?: (req) => string | undefined; // custom detection; undefined falls back to negotiation
contentLanguage?: boolean; // set Content-Language (+ Vary). Default true
queryParam?: string; // default "locale"
cookieName?: string; // default "generic-translation-locale"
}
Express / Connect — genericTranslationExpress(options?)
Sets req.locale and req.t, sends Content-Language and Vary: Accept-Language, and runs the
rest of the request inside the locale context.
app.use(genericTranslationExpress());
app.get("/", (req, res) => res.send(req.t("Hello!")));
TypeScript users can declare the added properties once:
import type { GenericTranslationRequestExtensions } from "@generic-translation/node";
declare global {
namespace Express {
interface Request extends GenericTranslationRequestExtensions {}
}
}
Resolve the locale from a signed-in user:
app.use(genericTranslationExpress({ locale: (req) => req.user?.locale }));
Fastify — genericTranslationFastify
import Fastify from "fastify";
import { genericTranslationFastify, type GenericTranslationRequestExtensions } from "@generic-translation/node";
declare module "fastify" {
interface FastifyRequest extends GenericTranslationRequestExtensions {}
}
const app = Fastify();
await app.register(genericTranslationFastify);
app.get("/", (request) => ({ message: request.t("Hello!") }));
request.locale and request.t are available from onRequest onwards; the async context
(getLocale(), getGenericTranslation() without arguments, formatters) is bound from preValidation, so it
is in place for validation, preHandler hooks and handlers. The plugin applies to the whole
instance it is registered on.
Hono — genericTranslationHono(options?)
import { Hono } from "hono";
import { genericTranslationHono, type GenericTranslationHonoVariables } from "@generic-translation/node";
const app = new Hono<{ Variables: GenericTranslationHonoVariables }>();
app.use(genericTranslationHono());
app.get("/", (c) => c.text(c.get("t")("Hello!")));
The locale context relies on AsyncLocalStorage, so run Hono on Node, Bun, Deno, or Cloudflare
Workers with the nodejs_compat flag.
Plain http
Use withRequestLocale, or call the Express middleware
directly — it only needs (req, res, next).
Other exports
| Export | Purpose |
|---|---|
getTranslations(locale?) |
The merged hash → translation map for a locale (e.g. to hand to a client). |
preloadTranslations(locales?) |
Warm the cache. |
clearTranslationCache(locale?) |
Drop loaded and runtime translations. |
getClient() |
The configured @generic-translation/core GenericTranslation API client. |
getDictionaryEntries() |
Flattened dictionary entries with hashes. |
clearMessages(), resetGenericTranslation() |
Test helpers. |
LOCALE_COOKIE, LOCALE_QUERY_PARAM, DEFAULT_CACHE_TTL_MS |
Constants. |
Types: GenericTranslationNodeOptions, TFunction, DFunction, TranslateValues, RegisteredMessage,
MsgOptions, TxOptions, TranslationMap, Dictionary, RuntimeMode, RequestLike,
RequestLocaleOptions, GenericTranslationMiddlewareOptions, GenericTranslationRequestExtensions, GenericTranslationHonoVariables,
GenericTranslationErrorInfo.
Testing your app
Give initializeGenericTranslation a loadTranslations function and no projectId, and nothing touches the
network:
import { hashSourceSync } from "@generic-translation/core";
import { initializeGenericTranslation, getGenericTranslation, resetGenericTranslation } from "@generic-translation/node";
beforeEach(() => {
resetGenericTranslation();
initializeGenericTranslation({
locales: ["es"],
loadTranslations: async () => ({ [hashSourceSync({ source: "Hello" })]: "Hola" }),
});
});
test("greets in Spanish", async () => {
expect((await getGenericTranslation("es"))("Hello")).toBe("Hola");
});
Something wrong or unclear on this page? Open an issue.