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: falseresult.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).
Options
Section titled “Options”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;}Returns
Section titled “Returns”interface TranslateResult { output: string | null; cached: boolean;}Streaming
Section titled “Streaming”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.
How it works
Section titled “How it works”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()returnfalse/nullon browsers without the API. The vanillatranslate()throwsTranslatorUnavailableError; the React hook surfacesstatus: "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 insessionStorage,cache: "local"forlocalStorage, or any{ get, set }-shaped object for a custom backend.
Caching
Section titled “Caching”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 sessionStoragetranslate({ input: text, sourceLanguage: "en", targetLanguage: "pt", cache: "session",});
// Persistent caching across tabstranslate({ 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.
Aborting
Section titled “Aborting”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();Errors and unavailability
Section titled “Errors and unavailability”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;}