Skip to content

Translator API

Building block for the Web’s Built-in Translator API (on-demand language packs). String-mode translation with pair-cached sessions, opt-in result caching, AbortSignal-driven cleanup. See useTranslator for React.

import { translate } from "@web-ai-sdk/translator";
const result = await translate({
input: "Hello, world.",
sourceLanguage: "en",
targetLanguage: "pt",
});
console.log(result.output); // → "Olá, mundo."
console.log(result.cached); // → 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;
signal?: AbortSignal;
}
NameTypeDescription
input requiredstringText to translate. Empty / whitespace resolves to { output: null }.
sourceLanguage requiredstringBCP-47 source language (e.g. pt, pt-BR). Regional tags are normalized to their base.
targetLanguagestringBCP-47 target language. Defaults to "en".
monitor(m) => voidObserve the first-call model download.
cache"session" | "local" | { get, set }Opt-in result cache.
cacheKeystringOverride the default cache key (JSON array string of normalized [sourceLanguage, targetLanguage, input]).
signalAbortSignalAbort signal.
interface TranslateResult {
output: string | null;
cached: boolean;
}

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.

AbortSignal is supported. Aborting mid-call throws AbortError; the cache is not written for aborted runs.

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;
}