DocsQuickstarts

Quickstart - Node and Express

Translate API responses, emails and server-rendered text in a Node service with request-scoped locales.

On this page

This adds Spanish and French to an Express server using @generic-translation/node. The same approach works with Fastify, Hono and plain http; see the Node reference.

1. Install

@generic-translation/node and @generic-translation/core are not published to npm yet. Clone the parent repository and link the built packages.

git clone --recurse-submodules https://github.com/generic-translation/generic-translation.git
for p in core node cli; do (cd generic-translation/packages/$p && pnpm install && pnpm build); done
{
  "dependencies": {
    "@generic-translation/core": "link:../generic-translation/packages/core",
    "@generic-translation/node": "link:../generic-translation/packages/node"
  },
  "devDependencies": {
    "@generic-translation/cli": "link:../generic-translation/packages/cli"
  }
}

2. Initialise and use

// server.ts
import express from "express";
import { initializeGenericTranslation, genericTranslationExpress, getGenericTranslation } from "@generic-translation/node";

initializeGenericTranslation({
  defaultLocale: "en",
  locales: ["es", "fr"],
  projectId: process.env.GENERIC_TRANSLATION_PROJECT_ID, // published translations are read from the 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,
    }),
  );
});

async function shippedEmail() {
  const t = await getGenericTranslation(); // uses the locale bound to the current request
  return t("Your order has shipped", { $context: "email subject" });
}

app.listen(3000);

The locale of each request is negotiated from ?locale=, the generic-translation-locale cookie, then Accept-Language.

curl -H "Accept-Language: es" localhost:3000/

Until the messages have been translated, every string renders as its English source.

3. Get translations

Strings reach the API in one of three ways. Pick one.

Submit your messages with getMessages(). Declare messages at module scope with msg(), then submit everything registered so far in a small script, wait for the job, and publish:

// scripts/translate.ts
import { getClient, getMessages } from "@generic-translation/node";
import "../src/messages"; // modules that call msg()

const client = getClient(); // needs GENERIC_TRANSLATION_PROJECT_ID and an API key with translations:enqueue
const { jobId } = await client.submitEntries({ entries: getMessages(), locales: ["es", "fr"] });
await client.waitForJob(jobId);
await client.publish({ locales: ["es", "fr"] }); // then the CDN serves them

With projectId set in initializeGenericTranslation, the server reads the published maps from the CDN.

Let the CLI find them. generic-translation translate also scans @generic-translation/node code: t("...") where t comes from getGenericTranslation(), msg("..."), req.t("...") in files that import from @generic-translation/node, and dictionary entries. Set src to include your server directories (generic-translation init adds server/, api/, routes/ and src/server/ when it finds a Node server dependency). tx() translates arbitrary runtime text and is never extracted. The full list of recognised patterns is on the CLI commands page.

Translate at runtime. See below.

Either way, you can also write maps to disk and point @generic-translation/node at the folder:

initializeGenericTranslation({
  defaultLocale: "en",
  locales: ["es", "fr"],
  translationsDir: "./translations", // reads translations/es.json, translations/fr.json
});

Sources are tried in order: loadTranslations, translationsDir, then the CDN.

4. Optional: translate on demand

With projectId, an apiKey that has the translations:generate permission, and runtimeTranslation: true, strings with no translation are translated when first needed and cached. Keep that key on the server. Full details in Runtime translation.

Something wrong or unclear on this page? Open an issue.

Type to search the documentation.