Build a browser AI app with transformers.js

By Ryze AI Team

This tutorial builds a small sentiment analysis app that runs entirely in the browser using transformers.js, with no backend.

Install

npm install @xenova/transformers. Or use a CDN import in a plain HTML file.

Basic usage

import { pipeline } from '@xenova/transformers';
const classifier = await pipeline('sentiment-analysis');
const result = await classifier('I love this product');
console.log(result); // [{label: 'POSITIVE', score: 0.9998}]

The first call downloads the model; subsequent calls use the cache.

Choose a device

Pass a device option for speed:

const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english', { device: 'webgpu' });

Use 'webgpu' where supported and fall back to 'wasm'. Show a loading bar while the model downloads, since the first load can take several seconds.

Move work to a Web Worker

Inference blocks the main thread. Create a worker that loads the pipeline and handles messages, so the UI stays responsive:

// worker.js
import { pipeline } from '@xenova/transformers';
let classifier;
self.onmessage = async (e) => {
  if (!classifier) classifier = await pipeline('sentiment-analysis');
  const result = await classifier(e.data);
  self.postMessage(result);
};

Caching and offline

Models are cached in IndexedDB automatically, so repeat visits are fast and the app works offline after the first load. Set env.allowLocalModels = false if you only want to load from the hub.

Tips

Pick small models; anything over a few hundred megabytes is a poor fit for a browser. Test on a mid-range phone over a throttled network. Show progress, handle errors gracefully, and never block the UI thread. For heavy generation, use a server instead.

Docs: transformers.js.