Call the API from JavaScript

Translate JSON from a Node.js server, wait for the result, and save it to a file.

Use native fetch to translate structured content from your server. This example translates an English account-settings heading into French and saves it as settings.fr.json. You need Node.js 22 or later and an engine configured with a translation model.

Keep credentials on the server. The React runtime renders catalogs without an API key.

Configure the request #

Create an API key with translation access to your engine and find the organization and engine IDs. For this example, use an engine with human review disabled.

sh
export LINGO_API_KEY="YOUR_API_KEY"
export LINGO_ORGANIZATION_ID="YOUR_ORGANIZATION_ID"
export LINGO_ENGINE_ID="YOUR_ENGINE_ID"
export LINGO_REQUEST_ID="settings-v1-fr"

Reuse LINGO_REQUEST_ID when retrying this submission. Choose a new value when the source, locales, or other request options change.

Translate and save the result #

Save this as translate.mjs:

js
import { writeFile } from "node:fs/promises";
import { setTimeout as delay } from "node:timers/promises";

const apiKey = process.env.LINGO_API_KEY;
const orgId = process.env.LINGO_ORGANIZATION_ID;
const engineId = process.env.LINGO_ENGINE_ID;
const requestId = process.env.LINGO_REQUEST_ID;
if (!apiKey || !orgId || !engineId || !requestId) {
  throw new Error("Set LINGO_API_KEY, LINGO_ORGANIZATION_ID, LINGO_ENGINE_ID, and LINGO_REQUEST_ID");
}

async function request(path, options = {}) {
  const response = await fetch(new URL(path, "https://api.lingo.dev"), {
    ...options,
    headers: { "X-API-Key": apiKey, ...options.headers },
    signal: AbortSignal.timeout(30_000),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  return response;
}

let job = await (
  await request(`/v2/organizations/${encodeURIComponent(orgId)}/localization/jobs`, {
    method: "POST",
    headers: { "Content-Type": "application/json", "Idempotency-Key": requestId },
    body: JSON.stringify({
      engineId,
      sourceLocale: "en",
      targetLocales: ["fr"],
      documents: [
        {
          key: "settings.json",
          format: { type: "json" },
          source: { content: { heading: "Account settings" } },
        },
      ],
    }),
  })
).json();
await writeFile("job.json", JSON.stringify({ id: job.id, requestId }, null, 2));
if (job.uploads.length) throw new Error("Upload the missing artifacts before starting");

const jobPath = `/v2/localization/jobs/${encodeURIComponent(job.id)}`;
job = await (await request(`${jobPath}/start`, { method: "POST" })).json();

const deadline = Date.now() + 120_000;
while (["Pending", "Running"].includes(job.status._tag)) {
  if (Date.now() >= deadline) throw new Error(`Still waiting for ${job.id}; keep job.json and check again later`);
  await delay(2000);
  job = await (await request(jobPath)).json();
}

const target = job.documents
  .find((document) => document.key === "settings.json")
  ?.targets.find((item) => item.locale === "fr");
if (target?.status._tag !== "Completed") {
  throw new Error(`Translation did not complete: ${JSON.stringify(job.status)}`);
}
const translated = await (await request(target.status.downloadUrl)).json();
if (typeof translated.heading !== "string") throw new Error("The result is missing its heading");
await writeFile("settings.fr.json", JSON.stringify(translated, null, 2) + "\n");
console.log("Saved settings.fr.json");

Run node translate.mjs, then open settings.fr.json and inspect the French heading. The program saves the job ID before starting work and downloads the result only after the target completes.

The request helper checks HTTP status before reading a response. For an HTTP error, use the status and problem details to decide what to correct. A network error or timeout can occur after the server accepts work.

Continue after an interruption #

Read the ID from job.json and retrieve the job to continue checking it. If the create response was lost before the file was saved, repeat the same request with the same idempotency key. Repeating /start continues the same job. A timeout ends the program's wait without cancelling server work.

For an application that handles many submissions or waits for human review, build a translation workflow that stores job IDs and source revisions and collects results in a worker. Translate files covers artifact uploads and partial results across several languages.