How to Build a Translator with Chrome’s Built-In AI — Opportunihub
Course Remote

How to Build a Translator with Chrome’s Built-In AI

David Aniebo · Remote

At a glance

Type
Course
Organisation
David Aniebo
Location
Remote
Work mode
Remote
Deadline
Rolling / not stated
Posted
17 Nov 2026

About this course

<p>Most translation features work the same way. The user types text, your app sends it to a translation API, and the API sends a translation back. That works, but every request adds cost and latency, and your users' text leaves their device.</p> <p>Chrome now ships two built-in AI APIs that change this: the <strong>Translator API</strong> and the <strong>Language Detector API</strong>. Chrome downloads small, specialized models on demand and runs them on the user's device. You don't host a model, run an inference server, or pay per request. You call a JavaScript API.</p> <p>In this tutorial, you'll build a translator in Next.js that:</p> <ul> <li>Detects the language of the text a user types.</li> <li>Translates it into a language they choose.</li> <li>Streams the translation into the page as Chrome produces it.</li> <li>Shows language-pack download progress, and lets the user cancel.</li> <li>Copies the translation, reads it aloud, and swaps the two languages.</li> <li>Handles browsers that don't support the APIs.</li> </ul> <h2 id="heading-table-of-contents">Table of Contents</h2> <ol> <li><a href="#heading-prerequisites">Prerequisites</a></li> <li><a href="#heading-internationalization-vs-ai-translation">Internationalization vs AI Translation</a></li> <li><a href="#heading-how-chromes-built-in-ai-apis-work">How Chrome's Built-In AI APIs Work</a></li> <li><a href="#heading-try-the-apis-in-the-playground-first">Try the APIs in the Playground First</a></li> <li><a href="#heading-how-to-set-up-the-nextjs-project">How to Set Up the Next.js Project</a></li> <li><a href="#heading-how-to-define-the-languages">How to Define the Languages</a></li> <li><a href="#heading-how-to-wrap-the-chrome-apis">How to Wrap the Chrome APIs</a></li> <li><a href="#heading-how-to-build-the-translation-hook">How to Build the Translation Hook</a></li> <li><a href="#heading-how-to-build-the-interface">How to Build the Interface</a></li> <li><a href="#heading-how-to-run-and-test-the-app">How to Run and Test the App</a></li> <li><a href="#heading-limitations-and-production-considerations">Limitations and Production Considerations</a></li> <li><a href="#heading-conclusion">Conclusion</a></li> </ol> <h2 id="heading-prerequisites">Prerequisites</h2> <p>You should be comfortable with:</p> <ul> <li>JavaScript or TypeScript</li> <li>React basics (components, props, <code>useState</code>, <code>useEffect</code>)</li> <li>Running commands in a terminal</li> </ul> <p>You'll need:</p> <ul> <li>Node.js 20.9 or later.</li> <li><strong>Desktop Chrome 138 or later.</strong> The Translator and Language Detector APIs work in Chrome on desktop. They don't work on mobile devices, and Firefox and Safari don't support them. Chrome's browser-support table also lists Edge (148). I tested this tutorial in Chrome 156 on macOS.</li> </ul> <p>You don't need to know anything about machine learning.</p> <h2 id="heading-internationalization-vs-ai-translation">Internationalization vs AI Translation</h2> <p>Before you write code, separate two ideas that are easy to confuse.</p> <p><strong>Internationalization (i18n)</strong> prepares your interface for multiple languages and regions: language selection, locale-aware dates, numbers and currencies, right-to-left (RTL) layout, and static interface strings that a person wrote and reviewed:</p> <pre><code class="language-ts">const messages = { en: { welcome: "Welcome", description: "Explore our platform" }, fr: { welcome: "Bienvenue", description: "Explorez notre plateforme" }, es: { welcome: "Bienvenido", description: "Explora nuestra plataforma" }, }; </code></pre> <p><strong>AI-powered translation</strong> generates translations on the fly for content nobody wrote ahead of time, such as comments, reviews, support messages and posts.</p> <table> <thead> <tr> <th>Traditional i18n</th> <th>AI-powered translation</th> </tr> </thead> <tbody><tr> <td>Uses predefined translations</td> <td>Generates translations dynamically</td> </tr> <tr> <td>Ideal for interface text</td> <td>Ideal for user-generated content</td> </tr> <tr> <td>Usually developer-managed</td> <td>Can process arbitrary text</td> </tr> <tr> <td>Predictable output</td> <td>Output may vary</td> </tr> </tbody></table> <p>AI translation complements i18n. It doesn't replace it. You still need curated strings for buttons and menus. The Translator API fills the gap for everything else.</p> <p>Chrome's documentation gives a good example: in a support chat, users write in their first language, and your site translates the message into your agent's language <em>before the message leaves the user's device</em>.</p> <h2 id="heading-how-chromes-built-in-ai-apis-work">How Chrome's Built-In AI APIs Work</h2> <p>There are two APIs, and they work together:</p> <ul> <li><code>LanguageDetector</code> takes text and returns a ranked list of languages, each with a confidence score between 0 and 1.</li> <li><code>Translator</code> is created for one language pair, such as English to Spanish, and translates text between them.</li> </ul> <p>Here's what makes them different from calling a cloud API, or from running a model yourself with a library such as Transformers.js:</p> <ol> <li><strong>The browser owns the model.</strong> You don't bundle or host model files. Chrome downloads them the first time a site needs them.</li> <li><strong>Translation uses language packs.</strong> Chrome's docs describe a language pack as "like a dictionary for a given language", downloaded on demand. The first translation for a pair triggers a download, and later ones reuse it.</li> <li><strong>Everything is asynchronous and permission-aware.</strong> You check <code>availability()</code> first, then call <code>create()</code>, and you can watch download progress.</li> </ol> <p>There are four constraints you need to design around, all from Chrome's documentation:</p> <ul> <li><strong>User activation.</strong> Creating a translator or detector needs a user gesture, such as a click, when a model has to be downloaded.</li> <li><strong>Not in Web Workers.</strong> Neither API is available in workers, so you call them from the main thread. (The calls are asynchronous and the model runs outside your JavaScript thread, so this doesn't block your UI.)</li> <li><strong>Sequential processing.</strong> Translations are processed one after another. A large request blocks later ones, so chunk work and show a loading indicator.</li> <li><strong>Top-level windows only.</strong> By default, the APIs work in top-level windows and same-origin iframes. Cross-origin iframes need a Permissions Policy <code>allow</code> attribute.</li> </ul> <p>The <code>availability()</code> method for both APIs returns one of four values, and your UI should handle each:</p> <table> <thead> <tr> <th>Value</th> <th>Meaning</th> </tr> </thead> <tbody><tr> <td><code>unavailable</code></td> <td>The browser doesn't support these options.</td> </tr> <tr> <td><code>downloadable</code></td> <td>Supported, but a model must be downloaded first.</td> </tr> <tr> <td><code>downloading</code></td> <td>Supported, and a download is already in progress.</td> </tr> <tr> <td><code>available</code></td> <td>Supported and ready to use with no download.</td> </tr> </tbody></table> <p>One privacy detail: Chrome hides the download status of specific language pairs to protect user privacy. Until your site creates a translator for a pair, all pairs are reported as <code>downloadable</code>.</p> <h2 id="heading-try-the-apis-in-the-playground-first">Try the APIs in the Playground First</h2> <p>Before you write code, experiment. The <a href="https://chrome.dev/web-ai-demos/built-in-ai-playground/">Built-in AI Playground</a> presents the AI features Chrome exposes as JavaScript APIs, including both of these. Open it in desktop Chrome and try this:</p> <ol> <li>Paste a few sentences in different languages into the language detector, and read the confidence scores.</li> <li>Try a single word, then a full sentence. Chrome's documentation warns that short input gives low-accuracy results, so compare the confidence values.</li> <li>Translate between a couple of language pairs. The first translation for a pair may pause while Chrome downloads a language pack.</li> </ol> <p>You'll build exactly this behaviour into the app.</p> <h2 id="heading-how-to-set-up-the-nextjs-project">How to Set Up the Next.js Project</h2> <p>Create a Next.js app with TypeScript and the App Router. Answer the remaining prompts however you like:</p> <pre><code class="language-bash">npx create-next-app@latest chrome-ai-translator --ts --app --no-tailwind --no-src-dir --import-alias "@/*" cd chrome-ai-translator </code></pre> <p>Then install the TypeScript definitions for Chrome's built-in AI APIs. TypeScript doesn't know about <code>Translator</code> or <code>LanguageDetector</code> yet, because they aren't in the standard DOM types:</p> <pre><code class="language-bash">npm install -D @types/dom-chromium-ai </code></pre> <p>The package declares <code>Translator</code>, <code>LanguageDetector</code> and the related types globally, so you don't import anything. Your editor will now autocomplete <code>Translator.create()</code> and flag mistakes.</p> <p>Delete <code>app/page.module.css</code> and the unused images in <code>public/</code>. You'll replace <code>app/page.tsx</code>, <code>app/layout.tsx</code> and <code>app/globals.css</code>. Create these folders next to <code>app/</code>:</p> <pre><code class="language-plaintext">chrome-ai-translator/ ├── app/ │ ├── globals.css │ ├── layout.tsx │ └── page.tsx ├── components/ │ ├── language-select.tsx │ ├── text-panel.tsx │ ├── translator-app.tsx │ └── unsupported-notice.tsx ├── hooks/ │ └── use-translation.ts └── lib/ ├── chrome-ai.ts └── languages.ts </code></pre> <p>Each folder has one job:</p> <ul> <li><code>lib/</code> contains plain TypeScript that talks to Chrome's APIs.</li> <li><code>hooks/</code> turns that into React state.</li> <li><code>components/</code> contains the UI.</li> <li><code>app/</code> contains the Next.js page and layout.</li> </ul> <h2 id="heading-how-to-define-the-languages">How to Define the Languages</h2> <p>Create <code>lib/languages.ts</code>. It lists the languages Chrome's Translator API supports (from <a href="https://developer.chrome.com/docs/ai/translator-api#supported-languages">Chrome's documentation</a>). The Translator API uses BCP 47 codes such as <code>es</code> or <code>zh-Hant</code>:</p> <pre><code class="language-ts">/** Sentinel value for "detect the source language for me". */ export const AUTO = "auto"; export interface Language { /** BCP 47 code, as expected by the Translator API. */ code: string; name: string; rtl?: boolean; } export const LANGUAGES: Language[] = [ { code: "ar", name: "Arabic", rtl: true }, { code: "de", name: "German" }, { code: "en", name: "English" }, { code: "es", name: "Spanish" }, { code: "fr", name: "French" }, { code: "he", name: "Hebrew", rtl: true }, // ...the full list of 39 languages is in the repository { code: "zh", name: "Chinese (Simplified)" }, { code: "zh-Hant", name: "Chinese (Traditional)" }, ]; export function languageName(code: string): string { return LANGUAGES.find((language) =&gt; language.code === code)?.name ?? code; } export function isRtl(code: string): boolean { return LANGUAGES.find((language) =&gt; language.code === code)?.rtl ?? false; } </code></pre> <p>A hard-coded list is fine for a tutorial, but Chrome says the list is specific to its implementation and subject to change, and there's no function yet to retrieve it dynamically. That's why the app still calls <code>Translator.availability()</code> before every translation. The list only decides what appears in the dropdowns.</p> <p>The <code>rtl</code> flag lets the output render right-to-left for Arabic and Hebrew.</p> <h2 id="heading-how-to-wrap-the-chrome-apis">How to Wrap the Chrome APIs</h2> <p>Now you'll create <code>lib/chrome-ai.ts</code>. This file is the heart of the project. It holds every call to Chrome's Translator and Language Detector APIs, so the rest of the app never touches them directly.</p> <p>You'll build it one piece at a time and add each piece below the previous one. Everything in this file runs in the browser only, so you'll import it from Client Components.</p> <h3 id="heading-step-1-add-the-shared-constants-types-and-errors">Step 1: Add the shared constants, types and errors</h3> <p>Start the file with a few small definitions that the later functions depend on:</p> <pre><code class="language-ts">/** * Thin helpers around Chrome's built-in Translator and Language Detector APIs. * Everything here runs in the browser only. Import it from Client Components. */ /** Below this confidence we ask the user to pick the language instead of guessing. */ export const CONFIDENCE_THRESHOLD = 0.6; export type DownloadProgress = (fraction: number) =&gt; void; export class LowConfidenceError extends Error { constructor() { super("We couldn't tell which language this is. Choose the source language manually."); } } export class UnsupportedPairError extends Error { constructor(source: string, target: string) { super(`Chrome can't translate from "${source}" to "${target}" on this device.`); } } </code></pre> <p>Here's what each piece does:</p> <ul> <li><code>CONFIDENCE_THRESHOLD</code> is the minimum confidence score we accept from the language detector. Detection is a probability, not a fact. Chrome's docs warn that very short phrases and single words give low-accuracy results, and recommend treating the result as unknown when confidence is too low. The hook you'll write later compares each result to this number. <code>0.6</code> is a starting point you can tune for your own users.</li> <li><code>DownloadProgress</code> is the type of the callback that receives download progress. Chrome reports progress as a fraction from <code>0</code> to <code>1</code>, so <code>0.5</code> means half of the language pack has downloaded.</li> <li><code>LowConfidenceError</code> is thrown when the detector can't tell what language the text is in. Giving it its own class lets the hook tell it apart from other failures, and its message tells the user what to do next.</li> <li><code>UnsupportedPairError</code> is thrown when Chrome says it can't translate between two languages. It includes both language codes, so the user knows which pair failed.</li> </ul> <h3 id="heading-step-2-check-whether-the-browser-supports-the-apis">Step 2: Check whether the browser supports the APIs</h3> <p>Add the feature-detection function:</p> <pre><code class="language-ts">/** Feature detection. Always false on the server, where `self.Translator` doesn't exist. */ export function isBuiltInAISupported(): boolean { return typeof self !== "undefined" &amp;&amp; "Translator" in self &amp;&amp; "LanguageDetector" in self; } </code></pre> <p>Next.js renders your components on the server first, and on the server there is no <code>self.Translator</code>. This function checks three things:</p> <ul> <li><code>typeof self !== "undefined"</code> makes sure we're in a context where <code>self</code> exists at all, so the function can't crash on the server.</li> <li><code>"Translator" in self</code> is the check Chrome's documentation recommends for the Translator API.</li> <li><code>"LanguageDetector" in self</code> is the matching check for the Language Detector API. The app needs both, so it only reports support when both exist.</li> </ul> <p>The function returns <code>true</code> or <code>false</code> and never throws. You'll use it later to decide whether to show the translator or a "not supported" notice.</p> <h3 id="heading-step-3-create-the-language-detector">Step 3: Create the language detector</h3> <p>Next, add the code that creates the detector. This is the first place you'll see the <code>monitor</code> callback and download progress:</p> <pre><code class="language-ts">let detectorPromise: Promise&lt;LanguageDetector&gt; | null = null; function getDetector(onProgress?: DownloadProgress) { detectorPromise ??= LanguageDetector.create({ monitor(monitor) { monitor.addEventListener("downloadprogress", (event) =&gt; onProgress?.(event.loaded)); }, }); // If creation fails (e.g. no user activation), allow a retry on the next click. detectorPromise.catch(() =&gt; { detectorPromise = null; }); return detectorPromise; } </code></pre> <p>Here's how <code>getDetector()</code> works:</p> <ul> <li><code>detectorPromise</code> is a module-level variable that holds the detector. We store the <strong>promise</strong>, not the finished detector. That way, if two parts of the app ask for a detector at the same moment, they share one creation instead of starting two.</li> <li><code>??=</code> means "assign only if the variable is <code>null</code> or <code>undefined</code>". The first call runs <code>LanguageDetector.create()</code>, and every later call reuses the stored promise.</li> <li>The <code>monitor</code> option is a callback that Chrome calls with a <code>CreateMonitor</code> object. We listen for its <code>downloadprogress</code> event and pass <code>event.loaded</code>, the 0-to-1 fraction, to <code>onProgress</code>. Chrome's detection model is small and may already be on the device, so this event might never fire. We still handle it, because it can fire the first time.</li> <li>The <code>.catch()</code> resets <code>detectorPromise</code> to <code>null</code> if creation fails. Without it, a failed attempt (for example, when Chrome needs a user click that it didn't get) would be cached forever, and the user could never retry.</li> </ul> <h3 id="heading-step-4-detect-the-language-of-some-text">Step 4: Detect the language of some text</h3> <p>Now add the function that uses the detector:</p> <pre><code class="language-ts">export interface Detection { language: string; confidence: number; } export async function detectLanguage( text: string, onProgress?: DownloadProgress, signal?: AbortSignal, ): Promise&lt;Detection | null&gt; { const detector = await getDetector(onProgress); // Results are ranked from most to least likely. The last entry is always "und" (undetermined). const [top] = await detector.detect(text, { signal }); if (!top?.detectedLanguage || top.detectedLanguage === "und") return null; return { language: top.detectedLanguage, confidence: top.confidence ?? 0 }; } </code></pre> <p>This is what the code does:</p> <ul> <li>The <code>Detection</code> interface describes what we return: a BCP 47 language code such as <code>"es"</code>, and a confidence score between <code>0</code> and <code>1</code>.</li> <li><code>detectLanguage()</code> first waits for the detector from <code>getDetector()</code>. It passes <code>onProgress</code> along so the UI can show a download bar.</li> <li><code>detector.detect(text, { signal })</code> returns a list of guesses ranked from most to least likely, each with a <code>detectedLanguage</code> and a <code>confidence</code>. The <code>signal</code> is an <code>AbortSignal</code>, so the user can cancel a detection in progress.</li> <li>The array destructuring <code>[top]</code> takes only the best guess.</li> <li>The last item in Chrome's results is always <code>und</code>, which means "undetermined". It's the probability that the text isn't in a language the model knows. If the best guess is missing or is <code>und</code>, the function returns <code>null</code>, which means "no answer".</li> <li>Otherwise, it returns the language and confidence. The <code>?? 0</code> is a safety net, because TypeScript types <code>confidence</code> as optional.</li> </ul> <h3 id="heading-step-5-create-and-cache-translators">Step 5: Create and cache translators</h3> <p>Translation is where the language-pair logic lives. Add this next:</p> <pre><code class="language-ts">// A Translator is tied to one language pair. Creating one is expensive, so we keep them around. const translators = new Map&lt;string, Translator&gt;(); export async function getTranslator( sourceLanguage: string, targetLanguage: string, onProgress?: DownloadProgress, signal?: AbortSignal, ): Promise&lt;Translator&gt; { const key = `${sourceLanguage}&gt;${targetLanguage}`; const cached = translators.get(key); if (cached) return cached; const availability = await Translator.availability({ sourceLanguage, targetLanguage }); if (availability === "unavailable") { throw new UnsupportedPairError(sourceLanguage, targetLanguage); } const translator = await Translator.create({ sourceLanguage, targetLanguage, signal, monitor(monitor) { monitor.addEventListener("downloadprogress", (event) =&gt; onProgress?.(event.loaded)); }, }); translators.set(key, translator); return translator; } </code></pre> <p>This function follows the lifecycle described in Chrome's documentation, in four stages:</p> <ol> <li><strong>Check the cache.</strong> A <code>Translator</code> is tied to exactly one language pair. Creating one is expensive, so we keep a <code>Map</code> of them, keyed by a string like <code>"en&gt;es"</code>. If we already have a translator for this pair, we return it immediately. That's why translating a second sentence is fast.</li> <li><strong>Check availability.</strong> <code>Translator.availability()</code> tells us whether Chrome can handle this pair. It returns <code>unavailable</code>, <code>downloadable</code>, <code>downloading</code> or <code>available</code>. If it's <code>unavailable</code>, we throw <code>UnsupportedPairError</code> before attempting anything else, so no download starts for a pair that can never work.</li> <li><strong>Create the translator.</strong> <code>Translator.create()</code> receives the language pair, the <code>signal</code> for cancellation, and a <code>monitor</code> that reports download progress exactly like the detector did. If a language pack has to be downloaded, Chrome starts the download automatically here. This is also the step that needs a user gesture, such as a click, when a download is required.</li> <li><strong>Store and return.</strong> We save the new translator in the <code>Map</code> for next time and return it.</li> </ol> <h3 id="heading-step-6-release-the-models-when-youre-done">Step 6: Release the models when you're done</h3> <p>Add a function that frees memory:</p> <pre><code class="language-ts">/** Releases the memory held by the models. Call it when the user leaves the feature. */ export async function destroyAll() { for (const translator of translators.values()) translator.destroy(); translators.clear(); const pending = detectorPromise; detectorPromise = null; (await pending?.catch(() =&gt; null))?.destroy(); } </code></pre> <p>MDN recommends calling <code>destroy()</code> once you've finished with a <code>Translator</code> or <code>LanguageDetector</code>, because they can use a lot of resources. This function does that for everything we created:</p> <ul> <li>The <code>for</code> loop calls <code>destroy()</code> on every cached translator, and <code>translators.clear()</code> empties the cache so a later request creates a fresh one.</li> <li>The detector is trickier, because we stored a promise rather than the detector itself. We copy the promise into <code>pending</code>, reset the shared variable to <code>null</code>, and then wait for the promise.</li> <li><code>pending?.catch(() =&gt; null)</code> handles two edge cases: there might be no detector at all, or creation might have failed. In both cases we get <code>null</code> back, and the final <code>?.destroy()</code> does nothing.</li> </ul> <p>The hook you'll write next calls <code>destroyAll()</code> when the component unmounts.</p> <h3 id="heading-step-7-turn-api-errors-into-helpful-messages">Step 7: Turn API errors into helpful messages</h3> <p>Finally, add the function that explains failures to the user:</p> <pre><code class="language-ts">/** Turns the DOMExceptions these APIs throw into messages a user can act on. */ export function describeError(error: unknown): string { if (error instanceof DOMException) { switch (error.name) { case "NotAllowedError": return "Chrome needs a fresh click to start the download. Press Translate again."; case "NotSupportedError": // Also thrown on a brand-new Chrome profile while it is still fetching its components. return "Chrome couldn't prepare this translation. If this is your first use, wait a moment and try again. Otherwise, this language may not be supported on your device."; case "QuotaExceededError": return "That text is too long. Try translating a shorter passage."; case "NetworkError": return "The language pack couldn't be downloaded. Check your connection and try again."; } } return error instanceof Error ? error.message : "Something went wrong."; } </code></pre> <p>The built-in AI APIs report problems by throwing a <code>DOMException</code>, and the exception's <code>name</code> says what went wrong. This function maps each name to a message a person can act on:</p> <ul> <li><code>NotAllowedError</code>: Chrome needed a user gesture, like a click, to start a download and didn't get one. Asking the user to press Translate again fixes it.</li> <li><code>NotSupportedError</code>: MDN documents this as the error thrown when the requested languages aren't supported. During testing I also saw it on a brand-new Chrome profile, on the very first attempt, while Chrome was still preparing its components. The next attempt worked. The message covers both cases.</li> <li><code>QuotaExceededError</code>: MDN documents this as the error thrown when the input is larger than the available quota. It means the text is too long.</li> <li><code>NetworkError</code>: the language pack couldn't be downloaded.</li> </ul> <p>For anything else, the function falls back to the error's own message if it's a normal <code>Error</code>, or to a generic message.</p> <p>Your <code>lib/chrome-ai.ts</code> file is now complete. In the next section, you'll use these functions from a React hook.</p> <h2 id="heading-how-to-build-the-translation-hook">How to Build the Translation Hook</h2> <p>Create <code>hooks/use-translation.ts</code>. It runs the whole flow (detect, check, translate) and exposes React state:</p> <pre><code class="language-ts">"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { AUTO } from "@/lib/languages"; import { CONFIDENCE_THRESHOLD, LowConfidenceError, describeError, destroyAll, detectLanguage, getTranslator, type Detection, } from "@/lib/chrome-ai"; export type Phase = "idle" | "detecting" | "preparing" | "translating"; export function useTranslation() { const [phase, setPhase] = useState&lt;Phase&gt;("idle"); const [downloadProgress, setDownloadProgress] = useState&lt;number | null&gt;(null); const [output, setOutput] = useState(""); const [detected, setDetected] = useState&lt;Detection | null&gt;(null); const [error, setError] = useState&lt;string | null&gt;(null); const controllerRef = useRef&lt;AbortController | null&gt;(null); // Free the models when the component unmounts. useEffect(() =&gt; { return () =&gt; { controllerRef.current?.abort(); void destroyAll(); }; }, []); const translate = useCallback(async (text: string, source: string, target: string) =&gt; { controllerRef.current?.abort(); const controller = new AbortController(); controllerRef.current = controller; const { signal } = controller; setError(null); setOutput(""); setDetected(null); setDownloadProgress(null); try { let from = source; if (source === AUTO) { setPhase("detecting"); const result = await detectLanguage(text, setDownloadProgress, signal); if (!result || result.confidence &lt; CONFIDENCE_THRESHOLD) throw new LowConfidenceError(); setDetected(result); from = result.language; } if (from === target) { throw new Error("The source and target languages are the same."); } setPhase("preparing"); setDownloadProgress(null); const translator = await getTranslator(from, target, setDownloadProgress, signal); setPhase("translating"); setDownloadProgress(null); // Streaming shows text as soon as it's ready, which feels faster for longer input. const reader = translator.translateStreaming(text, { signal }).getReader(); for (;;) { const { done, value } = await reader.read(); if (done) break; setOutput((current) =&gt; current + value); } } catch (caught) { if (!signal.aborted) setError(describeError(caught)); } finally { if (controllerRef.current === controller) { controllerRef.current = null; setPhase("idle"); setDownloadProgress(null); } } }, []); const cancel = useCallback(() =&gt; controllerRef.current?.abort(), []); const reset = useCallback(() =&gt; { setOutput(""); setDetected(null); setError(null); }, []); return { phase, downloadProgress, output, detected, error, translate, cancel, reset }; } </code></pre> <p>Here's what happens when the user clicks Translate:</p> <ol> <li><strong>Cancel anything in flight</strong> and create a new <code>AbortController</code>. Its <code>signal</code> goes into every call, so one <code>cancel()</code> stops detection, downloading and translating.</li> <li><strong>Detect, if needed.</strong> When the source is "Detect language", we call <code>detectLanguage()</code>. If the result is <code>null</code> or below the confidence threshold, we throw <code>LowConfidenceError</code>, and the user sees "Choose the source language manually."</li> <li><strong>Validate.</strong> Translating a language into itself is pointless, so we stop with a clear message.</li> <li><strong>Prepare the translator.</strong> This is the phase where a language pack may download, so <code>downloadProgress</code> updates the progress bar.</li> <li><strong>Translate with streaming.</strong> We use <code>translateStreaming()</code> and append each chunk to the output. In my test of a four-sentence passage, Chrome returned one chunk per sentence. The docs recommend streaming for longer text. For a short sentence, you get a single chunk, so it behaves the same as <code>translate()</code>.</li> </ol> <p>Note that we read the stream with <code>getReader()</code> instead of <code>for await</code>. <code>for await</code> over a <code>ReadableStream</code> needs the <code>dom.asynciterable</code> TypeScript lib, and <code>getReader()</code> works everywhere.</p> <p>The <code>finally</code> block only resets the UI if this call is still the current one. Without that check, a cancelled older request could reset the state of a newer one.</p> <p>The <code>useEffect</code> cleanup aborts any pending work and calls <code>destroyAll()</code> when the component unmounts, which releases the models.</p> <h2 id="heading-how-to-build-the-interface">How to Build the Interface</h2> <h3 id="heading-handling-server-rendering-safely">Handling server rendering safely</h3> <p>Create <code>components/translator-app.tsx</code>. The first decision is how to check browser support in a server-rendered app.</p> <p>You can't call <code>isBuiltInAISupported()</code> during render. The server would answer <code>false</code>, the browser would answer <code>true</code>, and React would report a hydration mismatch. <code>useSyncExternalStore</code> solves this cleanly, because it takes a separate snapshot for the server:</p> <pre><code class="language-tsx">const supported = useSyncExternalStore&lt;boolean | null&gt;( noopSubscribe, isBuiltInAISupported, // client snapshot () =&gt; null, // server snapshot ); </code></pre> <p>The server and the first client render both see <code>null</code>, so they match. React then switches to the real answer on the client. The app shows "Checking browser support…" for <code>null</code>, a notice for <code>false</code>, and the translator for <code>true</code>. Nothing is subscribed to, because browser support doesn't change while the page is open, so <code>noopSubscribe</code> does nothing.</p> <h3 id="heading-the-unsupported-notice">The unsupported notice</h3> <p>Browsers without the APIs get a clear explanation instead of a broken form. Create <code>components/unsupported-notice.tsx</code>:</p> <pre><code class="language-tsx">export function UnsupportedNotice() { return ( &lt;div className="notice" role="alert"&gt; &lt;h2&gt;This browser doesn&amp;apos;t support Chrome&amp;apos;s built-in translation&lt;/h2&gt; &lt;p&gt; The Translator and Language Detector APIs are available in Chrome on desktop (version 138 or later). They aren&amp;apos;t available on mobile, Firefox or Safari. &lt;/p&gt; &lt;p&gt; Open this page in desktop Chrome, or read about the APIs in the{" "} &lt;a href="https://developer.chrome.com/docs/ai/translator-api"&gt;Chrome documentation&lt;/a&gt;. &lt;/p&gt; &lt;/div&gt; ); } </code></pre> <h3 id="heading-the-language-selector">The language selector</h3> <p>Create <code>components/language-select.tsx</code>. A real <code>&lt;label&gt;</code> connected with <code>htmlFor</code> makes the control accessible and enlarges the click target:</p> <pre><code class="language-tsx">import { AUTO, LANGUAGES } from "@/lib/languages"; interface Props { id: string; label: string; value: string; onChange: (code: string) =&gt; void; /** Adds a "Detect language" option (source selector only). */ allowAuto?: boolean; } export function LanguageSelect({ id, label, value, onChange, allowAuto }: Props) { return ( &lt;div className="field"&gt; &lt;label htmlFor={id}&gt;{label}&lt;/label&gt; &lt;select id={id} value={value} onChange={(event) =&gt; onChange(event.target.value)}&gt; {allowAuto &amp;&amp; &lt;option value={AUTO}&gt;Detect language&lt;/option&gt;} {LANGUAGES.map((language) =&gt; ( &lt;option key={language.code} value={language.code}&gt; {language.name} &lt;/option&gt; ))} &lt;/select&gt; &lt;/div&gt; ); } </code></pre> <h3 id="heading-the-text-panel">The text panel</h3> <p>Create <code>components/text-panel.tsx</code>. One component serves as both the input and the output. It includes the copy and read-aloud buttons from the design:</p> <pre><code class="language-tsx">"use client"; import { useState } from "react"; interface Props { id: string; label: string; value: string; /** BCP 47 code of the text, so screen readers and speech use the right voice. */ lang?: string; rtl?: boolean; readOnly?: boolean; placeholder?: string; onChange?: (value: string) =&gt; void; } export function TextPanel({ id, label, value, lang, rtl, readOnly, placeholder, onChange }: Props) { const [copied, setCopied] = useState(false); async function copy() { await navigator.clipboard.writeText(value); setCopied(true); setTimeout(() =&gt; setCopied(false), 1500); } function speak() { // The Web Speech API is separate from the built-in AI APIs, and works in most browsers. speechSynthesis.cancel(); const utterance = new SpeechSynthesisUtterance(value); if (lang) utterance.lang = lang; speechSynthesis.speak(utterance); } return ( &lt;div className="field"&gt; &lt;label htmlFor={id} className="visually-hidden"&gt; {label} &lt;/label&gt; &lt;textarea id={id} rows={6} value={value} lang={lang} // dir="auto" lets the browser choose the direction of whatever the user types. dir={readOnly ? (rtl ? "rtl" : "ltr") : "auto"} readOnly={readOnly} placeholder={placeholder} onChange={(event) =&gt; onChange?.(event.target.value)} /&gt; &lt;div className="actions"&gt; &lt;button type="button" className="icon" onClick={copy} disabled={!value} aria-label={`Copy ${label.toLowerCase()}`}&gt; {copied ? "✓" : "⧉"} &lt;/button&gt; &lt;button type="button" className="icon" onClick={speak} disabled={!value} aria-label={`Read ${label.toLowerCase()} aloud`}&gt; 🔊 &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; ); } </code></pre> <p>Some details:</p> <ul> <li><strong>Copy</strong> uses the Clipboard API.</li> <li><strong>Read aloud</strong> uses the Web Speech API's <code>speechSynthesis</code>. It's a separate browser feature from the built-in AI APIs, and it works in most browsers. We set <code>utterance.lang</code> so the browser picks a matching voice.</li> <li><code>dir="auto"</code> on the input lets the browser choose the text direction from whatever the user types, so Arabic input works without extra logic.</li> <li>The output uses <code>lang</code> and <code>dir</code> from the target language, so screen readers pronounce it correctly and RTL scripts render properly.</li> <li>Both buttons have <code>aria-label</code>s, because their visible content is only an icon.</li> </ul> <h3 id="heading-putting-it-together">Putting it together</h3> <p>Here's the main component:</p> <pre><code class="language-tsx">"use client"; import { useState, useSyncExternalStore } from "react"; import { useTranslation } from "@/hooks/use-translation"; import { isBuiltInAISupported } from "@/lib/chrome-ai"; import { AUTO, isRtl, languageName } from "@/lib/languages"; import { LanguageSelect } from "./language-select"; import { TextPanel } from "./text-panel"; import { UnsupportedNotice } from "./unsupported-notice"; const noopSubscribe = () =&gt; () =&gt; {}; export function TranslatorApp() { // `null` on the server and during hydration, then the real answer on the client. // This avoids a hydration mismatch, because the server can't know what the browser supports. const supported = useSyncExternalStore&lt;boolean | null&gt;( noopSubscribe, isBuiltInAISupported, () =&gt; null, ); const { phase, downloadProgress, output, detected, error, translate, cancel, reset } = useTranslation(); const [source, setSource] = useState(AUTO); const [target, setTarget] = useState("es"); const [text, setText] = useState(""); if (supported === null) return &lt;p className="status"&gt;Checking browser support…&lt;/p&gt;; if (!supported) return &lt;UnsupportedNotice /&gt;; const busy = phase !== "idle"; const sourceLang = source === AUTO ? detected?.language : source; const statusMessage = (() =&gt; { if (error) return error; if (phase === "detecting") return "Detecting language…"; if (phase === "preparing") return "Preparing the translator…"; if (phase === "translating") return "Translating…"; if (detected &amp;&amp; source === AUTO) { return `Detected ${languageName(detected.language)} (${Math.round(detected.confidence * 100)}% confidence).`; } return ""; })(); function swap() { if (!sourceLang) return; setSource(target); setTarget(sourceLang); setText(output); reset(); } return ( &lt;form onSubmit={(event) =&gt; { event.preventDefault(); // This runs inside a click handler, so Chrome sees "user activation". // That's required before it will download a model. void translate(text.trim(), source, target); }} &gt; &lt;div className="grid"&gt; &lt;div className="column"&gt; &lt;LanguageSelect id="source-language" label="From" value={source} onChange={(code) =&gt; { setSource(code); reset(); }} allowAuto /&gt; &lt;TextPanel id="source-text" label="Source text" value={text} lang={sourceLang} placeholder="Type or paste text…" onChange={setText} /&gt; &lt;/div&gt; &lt;button type="button" className="swap" onClick={swap} disabled={busy || !sourceLang} aria-label="Swap languages" title="Swap languages" &gt; ⇄ &lt;/button&gt; &lt;div className="column"&gt; &lt;LanguageSelect id="target-language" label="To" value={target} onChange={setTarget} /&gt; &lt;TextPanel id="translation" label="Translation" value={output} lang={target} rtl={isRtl(target)} readOnly placeholder="The translation appears here." /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className="submit-row"&gt; {busy ? ( &lt;button type="button" className="secondary" onClick={cancel}&gt; Cancel &lt;/button&gt; ) : ( &lt;button type="submit" disabled={!text.trim()}&gt; Translate &lt;/button&gt; )} &lt;/div&gt; {downloadProgress !== null &amp;&amp; ( &lt;label className="progress"&gt; Downloading language pack… {Math.round(downloadProgress * 100)}% &lt;progress max={1} value={downloadProgress} /&gt; &lt;/label&gt; )} {/* A live region announces status changes and errors to screen readers. */} &lt;p role="status" aria-live="polite" className={error ? "status error" : "status"}&gt; {statusMessage} &lt;/p&gt; &lt;/form&gt; ); } </code></pre> <p>A few details are worth noting.</p> <p>The form's <code>onSubmit</code> handler calls <code>translate()</code>. Because it runs inside the click that submitted the form, Chrome sees user activation. That's what lets Chrome start a model download. Calling <code>Translator.create()</code> from a <code>useEffect</code> on page load would not have a user gesture.</p> <p>The swap button exchanges the two languages and moves the translation into the input box. If the source is "Detect language", it uses the language that was detected, and it's disabled until there is one.</p> <p>The status line is a <code>&lt;p role="status" aria-live="polite"&gt;</code>. Screen readers announce messages like "Translating…", the detection result, and errors without moving focus. The progress bar has a visible label.</p> <h3 id="heading-the-page-and-layout">The page and layout</h3> <p>Finally, wire it into the app. <code>app/page.tsx</code> is a Server Component that renders the client component:</p> <pre><code class="language-tsx">import { TranslatorApp } from "@/components/translator-app"; export default function Home() { return ( &lt;main&gt; &lt;h1&gt;Translate with Chrome&amp;apos;s built-in AI&lt;/h1&gt; &lt;p className="lede"&gt; Text is detected and translated on your device by Chrome. It isn&amp;apos;t sent to a translation server. &lt;/p&gt; &lt;TranslatorApp /&gt; &lt;/main&gt; ); } </code></pre> <p>And <code>app/layout.tsx</code>:</p> <pre><code class="language-tsx">import type { Metadata } from "next"; import "./globals.css"; export const metadata: Metadata = { title: "Translate with Chrome's built-in AI", description: "A Next.js app that translates text on-device using Chrome's Translator and Language Detector APIs.", }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( &lt;html lang="en"&gt; &lt;body&gt;{children}&lt;/body&gt; &lt;/html&gt; ); } </code></pre> <p>I won't reproduce the CSS here because none of it is specific to the APIs. Copy <code>app/globals.css</code> from the repository. It styles the two-column layout, the buttons and the progress bar, and collapses to one column on small screens.</p> <p>Notice the boundary: <code>app/page.tsx</code> and <code>app/layout.tsx</code> are Server Components, while <code>translator-app.tsx</code> starts with <code>"use client"</code>, so it and everything it imports run in the browser. That's the right place for the boundary, because everything that touches Chrome's APIs has to run on the client.</p> <h2 id="heading-how-to-run-and-test-the-app">How to Run and Test the App</h2> <p>Start the dev server and open the URL in <strong>desktop Chrome</strong>:</p> <pre><code class="language-bash">npm run dev </code></pre> <p>Then try these scenarios. Here's what I saw in Chrome 156 on macOS:</p> <table> <thead> <tr> <th>What I did</th> <th>What happened</th> </tr> </thead> <tbody><tr> <td>Typed "This is a test sentence." with the source set to <em>Detect language</em> and target <em>Spanish</em></td> <td>Detected "English (100% confidence)" and translated it to "Esta es una oración de prueba."</td> </tr> <tr> <td>Chose a language pair I hadn't used before (English to French)</td> <td>A progress bar counted up as the language pack downloaded, which took about 15 seconds on my connection, then the translation appeared.</td> </tr> <tr> <td>Translated a Spanish sentence into English</td> <td>Detected "Spanish (100% confidence)" and returned "Hello, how are you today? I hope everything goes well."</td> </tr> <tr> <td>Typed a Hausa sentence</td> <td>Chrome's detector recognised it (<code>ha</code>), but the translator reported that it can't translate from <code>ha</code> to English.</td> </tr> </tbody></table> <p>The Hausa result is a good lesson. Language <em>detection</em> and language <em>translation</em> support different sets of languages. Chrome's translator list doesn't include Hausa, Yoruba or Igbo, so for those languages you'd need a different approach, such as a server-side model or a cloud translation API.</p> <p>Also try the edge cases:</p> <ul> <li>Click <strong>Cancel</strong> while a language pack downloads.</li> <li>Enter a single word with <em>Detect language</em> selected. Detection is much less reliable on short input, so you may be asked to choose the language yourself.</li> <li>Pick the same language for both sides.</li> </ul> <p>If your first attempt in a brand-new Chrome profile fails with a "couldn't prepare this translation" message, wait a moment and try again. In my first run in a fresh profile, Chrome threw a <code>NotSupportedError</code> before it succeeded on the next attempt, which is why <code>describeError</code> explains it rather than blaming the language.</p> <h2 id="heading-limitations-and-production-considerations">Limitations and Production Considerations</h2> <p>The built-in AI APIs make the translation code small, but they come with constraints you should plan for.</p> <h3 id="heading-browser-support">Browser support</h3> <p>These are Chrome (and Edge) on desktop features. Treat them as progressive enhancement:</p> <ul> <li>Feature-detect with <code>"Translator" in self</code> before using them, as you did.</li> <li>Provide a fallback for everyone else, such as a cloud translation API, and tell users when their text will leave the device.</li> <li>Don't hide the rest of your product behind the feature.</li> </ul> <h3 id="heading-privacy">Privacy</h3> <p>Be precise about what "private" means:</p> <ul> <li><strong>Translation and detection run locally.</strong> The text isn't sent to a translation API.</li> <li><strong>Model downloads still happen.</strong> Chrome downloads language packs over the network the first time a pair is used.</li> <li>Make sure your own analytics and error logging never capture the text users translate.</li> </ul> <h3 id="heading-quality-and-honesty">Quality and honesty</h3> <ul> <li>Language detection is probabilistic. Show confidence, set a threshold, and let users override it.</li> <li>Chrome's docs warn that the detector can't identify every language with complete accuracy.</li> <li>Don't rely on machine translation alone for legal, medical, financial or other high-stakes content, and have native speakers review output for the languages you ship.</li> </ul> <h3 id="heading-performance-and-resources">Performance and resources</h3> <ul> <li><strong>Chunk long input.</strong> Translations are processed sequentially, so a long text delays everything behind it. Show a loading state and split big documents.</li> <li><strong>Check the quota.</strong> Some implementations limit input size. A <code>Translator</code> exposes <code>inputQuota</code> and <code>measureInputUsage()</code>, so you can check before translating (this is the pattern from MDN, which I haven't wired into this demo):</li> </ul> <pre><code class="language-ts">const translator = await getTranslator("en", "es"); const usage = await translator.measureInputUsage(text); if (usage &gt; translator.inputQuota) { throw new Error("That text is too long to translate in one go."); } </code></pre> <ul> <li><strong>Release resources.</strong> Call <code>destroy()</code> on translators you no longer need, as <code>destroyAll()</code> does.</li> </ul> <h3 id="heading-embedding-and-workers">Embedding and workers</h3> <ul> <li>The APIs aren't available in Web Workers, so you can't move them off the main thread the way you would with a library such as Transformers.js.</li> <li>Cross-origin iframes need a Permissions Policy <code>allow</code> attribute to use them.</li> </ul> <h2 id="heading-conclusion">Conclusion</h2> <p>You built a Next.js translator that runs on-device with no model hosting and no inference backend. Along the way, you used the main parts of the Translator and Language Detector APIs: feature detection, <code>availability()</code>, <code>create()</code> with download progress, <code>detect()</code> with confidence scores, <code>translateStreaming()</code>, cancellation with <code>AbortController</code>, and <code>destroy()</code>.</p> <p>You also dealt with the problems that browser-based AI introduces in a server-rendered framework: the server has no <code>Translator</code>, models download on demand and need a user gesture, support is limited to some browsers, and the quality varies by language.</p> <p>Browser-based AI doesn't replace server-side AI. It gives you another option, one that can reduce cost and latency and keep ephemeral user text on the device. Where Chrome supports it, you now have a small, standards-based way to build multilingual experiences.</p>

How to apply

  1. 1 Read the full details above and confirm you meet the eligibility criteria.
  2. 2 Prepare your documents — an updated CV, and any cover letter, proposal or certificates required.
  3. 3 Click Apply on official site to complete your application on David Aniebo’s official page.
  4. 4 Submit as early as possible — many close once filled.
Apply on official site

Sourced from freecodecamp. Always verify details on the official website. Opportunihub never charges you to apply.

Frequently asked questions

How do I apply for How to Build a Translator with Chrome’s Built-In AI?

Review the full details and eligibility on this page, prepare your documents, then use the “Apply on official site” button to complete your application on David Aniebo’s official page.

Is this opportunity remote or location-based?

This opportunity is remote-friendly and open to applicants who can work from anywhere.

Is How to Build a Translator with Chrome’s Built-In AI free to apply for?

Opportunihub lists this Course for free. Legitimate Courses do not ask for payment to apply — never pay a fee to submit an application.