Extract and load message catalogs
Extract source messages, retrieve a translated JSONC file, and build a runtime map using the matching source metadata.
A component contains the source message and its context. Extraction collects those calls into a file that can be translated. Loading connects the translated values back to the component's keys. This recipe takes the first greeting through that file workflow and produces the Messages map a provider needs.
Extract the source #
Install the CLI and loader dependencies in the application:
npm install --save-dev @lingo.dev/cli@latest
npm install @lingo.dev/spec@1.17.1 jsonc-parser
npx lingo extract --src src --source-locale enExtraction runs locally and needs no API key. By default it writes locales/en.jsonc and lingo.d.ts. Explicit --out and --types flags override configured i18n.messagesPath and i18n.typesPath, which override those defaults. A Pages application with calls outside src uses its actual directory, such as --src pages.
Inspect the greeting's entry. Its value is the complete English template; the key comes from the source and context. The preceding comments record @context for meaning, @src for source location, and @orphan when a formerly extracted entry is no longer active. Review those changes before requesting translations.
Translate the selected catalog #
For an application without a Lingo.dev configuration, initialize this exact file and the Spanish target, then authenticate and link a localization engine:
npx lingo init --source en --targets es --files 'locales/en.jsonc' --yes
npx lingo login
npx lingo linkYou need access to an enabled localization engine and sufficient account usage. CLI authentication explains credentials for unattended runs.
If .lingo/config.json already exists, preserve its binding and other file entries. Add or update the entry selecting locales/en.jsonc and confirm that the project's source locale is en. For an existing baseline, finish ordinary updates for the existing target locales with npx lingo push --wait, resolve any review or failure, and inspect the retrieved changes before adding es to targetLocales. Keep the source revision fixed through the subsequent backfill. Add a language explains this order. Do not use init --force to make the configuration edit; it rebuilds file entries and can discard advanced options. Configuration covers the complete shape.
For the new project, or after completing that existing-project preparation, request missing target files and wait for their retrieval. Keep target files unchanged while this command waits, because its download path can overwrite local edits:
npx lingo push --backfill-missing --waitWhen the run finishes, inspect locales/es.jsonc. Resolve any reported review or failure state before treating the output as complete. For later source changes, extract again and use npx lingo push --wait; backfill is for missing files, not ordinary updates to an existing target.
Keep source metadata with the target revision #
The general JSONC translation workflow keeps the source's @orphan marks in the target but drops its @context and @src comments. A target alone cannot tell a loader which page owned a message.
Keep the extracted source file from the same revision as the target. Select active entries from that source and join their keys to the target's translated values. This excludes removed messages and preserves the option to select by source route. Missing target keys remain absent, allowing the runtime's source fallback.
Parse a raw catalog #
Create src/catalog.ts with this application-owned loader:
import { parse, type ParseError } from "jsonc-parser";
import { getActiveEntries, readLocaleFile, type LocaleEntry } from "@lingo.dev/spec";
import type { Messages } from "@lingo.dev/react";
function readStringCatalog(raw: string) {
const errors: ParseError[] = [];
const value: unknown = parse(raw, errors, { allowTrailingComma: true });
if (
errors.length > 0 ||
value === null ||
typeof value !== "object" ||
Array.isArray(value) ||
Object.values(value).some((entry) => typeof entry !== "string")
) {
throw new Error("Expected a flat JSONC object with string values");
}
return readLocaleFile(raw);
}
export function loadMatchedMessages(
sourceJsonc: string,
targetJsonc: string,
include: (entry: LocaleEntry) => boolean = () => true,
): Messages {
const active = getActiveEntries(readStringCatalog(sourceJsonc).entries);
const target = new Map(readStringCatalog(targetJsonc).entries.map((entry) => [entry.key, entry.value]));
return Object.fromEntries(
active.filter(include).flatMap((entry) => {
const value = target.get(entry.key);
return value === undefined ? [] : [[entry.key, value]];
}),
);
}readLocaleFile parses JSONC syntax and metadata, but it is not a runtime shape validator. It accepts arrays and non-string values despite its declared entry type, and returns no entries for primitive or null roots. The first function above rejects those shapes before the values can reach the renderer. Both functions are local and perform no I/O.
In a Vite application, load the files as raw text in the module that supplies the provider:
import source from "../locales/en.jsonc?raw";
import target from "../locales/es.jsonc?raw";
import { loadMatchedMessages } from "./catalog";
export const spanishMessages = loadMatchedMessages(source, target);This assumes the module is directly under src and Vite's client types are included. Pass spanishMessages as messages with locale="es". The greeting should now use the retrieved Spanish template and still replace {name} with Ana. Inspect the actual wording and test missing entries; loading a file is separate from judging its language quality.
Select only the source entries a route needs #
The optional include predicate runs on active source entries before the join. A page loader can use entry.metadata.src to include its own calls and shared components. Do that selection on the source, where the metadata still exists. Preserve source and target together when deploying so route selection does not use another revision's keys.
The Next Pages recipe supplies a complete route predicate. The TanStack recipe uses this loader for its request catalog. Their built-in loaders can filter metadata-bearing files, but neither automatically joins comment-free targets to source metadata.
Spec helper reference #
| Export | Contract |
|---|---|
readLocaleFile(content): LocaleFile | Parse JSONC, including trailing commas, and preceding metadata block comments; syntax errors throw. |
getActiveEntries(entries): LocaleEntry[] | Keep entries without truthy metadata.orphan. |
LocaleFile | { entries: LocaleEntry[] }. |
LocaleEntry | { key: string; value: string; metadata: EntryMetadata }. |
EntryMetadata | Optional context, src, and orphan. |
computeKey(source, context?) | Shared normalized source/context identity, also exported by React. |
buildIcuPlural(forms) | Emit known cardinal categories in canonical order. |
buildIcuSelect(forms) | Emit alternatives with sorted keys. |
The ICU builders accept string records; the React plural and select types add their required other form. The resulting runtime catalog is a plain Messages map, not a LocaleFile.
Existing keyed resources, documents, and static TypeScript locale modules use their own format handlers rather than this extraction recipe. The example projects show those layouts alongside React applications.