Skip to content

Translator API

This package wraps the built-in Translator API. It adds streaming, pair-based session reuse, optional result caching, and abort cleanup. For React, see useTranslator.

Before shipping, review the Production checklist for task-relevant input, safe rendering, progress, reversible changes, and cache freshness.

Use prepareTranslator to warm a session on user intent and release it when the feature closes. See the Session lifecycle guide.

import { translate } from "@web-ai-sdk/translator";
const result = await translate({
input: "Hello, world.",
sourceLanguage: "en",
targetLanguage: "pt",
});
console.log(result.output); // result: "Olá, mundo."
console.log(result.cached); // result: false

result.output is the translated text, or null when the input is empty or when sourceLanguage and targetLanguage match (the wrapper short-circuits same-language calls).

interface TranslateOptions {
input: string;
sourceLanguage: string;
targetLanguage?: string;
monitor?: (m: TranslatorMonitor) => void;
cache?: "session" | "local" | { get, set };
cacheKey?: string;
cacheTtl?: number; // built-in shortcut TTL in ms; default 1 hour
cacheRefresh?: boolean; // skip the cache read, write the fresh result
onUpdate?: (text: string) => void;
signal?: AbortSignal;
}
Name Type Description
input required string Text to translate. Empty / whitespace resolves to { output: null }.
sourceLanguage required string BCP-47 source language (e.g. pt, pt-BR). Regional tags are normalized to their base.
targetLanguage string BCP-47 target language. Defaults to "en".
monitor (m) => void Observe the first-call model download.
cache "session" | "local" | { get, set } Opt-in result cache.
cacheKey string Override the default cache key (JSON array string of normalized [sourceLanguage, targetLanguage, input]).
cacheTtl number TTL in milliseconds for entries written by the built-in "session" / "local" shortcuts. Defaults to one hour. Ignored by custom { get, set } caches.
cacheRefresh boolean Skip the cache read and replace the cached value after a successful run. The refreshed run reports cached: false.
onUpdate (text: string) => void Streaming update callback. Receives the cumulative buffer, not deltas.
signal AbortSignal Abort signal. Forwarded to the native translation operation.
interface TranslateResult {
output: string | null;
cached: boolean;
}

Pass onUpdate to receive partial output while the model translates. The wrapper consumes the native translateStreaming() method when the implementation provides it.

const result = await translate({
input: "Hello, world.",
sourceLanguage: "en",
targetLanguage: "pt",
onUpdate: (text) => console.log("partial", text),
});

onUpdate receives the cumulative translation so far, not raw deltas. Each update contains every previous update as a prefix, so you can render it directly. On implementations without translateStreaming(), the wrapper runs the one-shot method and delivers the result as a single final update.

Only the final completed output enters the result cache. Partial, aborted, or failed output is never cached.

Chrome’s Translator exposes Translator.create({ sourceLanguage, targetLanguage }) to spin up a session and translator.translate(text) to run it. The wrapper does three things on top:

  • Feature detection. isAvailable() / checkAvailability() return false / null on browsers without the API. The vanilla translate() throws TranslatorUnavailableError; the React hook surfaces status: "unavailable".
  • Session reuse by pair. Internally caches Translator.create() keyed by {sourceLanguage, targetLanguage}. Switching back and forth between two language pairs reuses the warm sessions.
  • Optional result cache. Off by default. Pass cache: "session" to memoize translations in sessionStorage, cache: "local" for localStorage, or any { get, set }-shaped object for a custom backend.
import { translate } from "@web-ai-sdk/translator";
// Off by default; every call hits the model.
translate({ input: text, sourceLanguage: "en", targetLanguage: "pt" });
// Per-tab caching via sessionStorage
translate({
input: text,
sourceLanguage: "en",
targetLanguage: "pt",
cache: "session",
});
// Persistent caching across tabs
translate({
input: text,
sourceLanguage: "en",
targetLanguage: "pt",
cache: "local",
});

The default cache key is JSON.stringify([source, target, trimmedInput]), so identical input/pair combinations hit. Pass cacheKey explicitly for finer-grained invalidation.

Built-in "session" / "local" entries expire after one hour by default. Pass cacheTtl (milliseconds) to change the TTL per call. Pass cacheRefresh: true to skip the read and replace the cached value after a successful run. Custom { get, set } caches own their expiry policy.

AbortSignal is supported. The wrapper forwards it to the native translate() and translateStreaming() operations, so browsers that honor the operation signal stop native work promptly. Aborting mid-call throws AbortError; the cache is not written for aborted runs. Aborting one call keeps the shared warm session usable for other callers.

const controller = new AbortController();
translate({
input: "long text…",
sourceLanguage: "en",
targetLanguage: "pt",
signal: controller.signal,
});
controller.abort();

The vanilla translate() throws TranslatorUnavailableError when the API is missing or reports availability: "unavailable". Callers branch explicitly:

import { translate, TranslatorUnavailableError } from "@web-ai-sdk/translator";
try {
const result = await translate({
input: text,
sourceLanguage: "en",
targetLanguage: "pt",
});
} catch (err) {
if (err instanceof TranslatorUnavailableError) {
return null;
}
throw err;
}