AI · Nov 23, 2026 · 10 min read

Transformers.js v2 in Next.js 15: Client-Side ML Inference

Hands-on guide to running sentiment analysis, translation, zero-shot classification, embeddings and image tasks in the browser with Transformers.js v2 and Next.js 15. Covers setup, concrete code examp

Transformers.js v2 in Next.js 15: Client-Side ML Inference

Why Client-Side Inference Matters in 2025

Running machine learning models directly in the browser eliminates round-trip latency to remote APIs, preserves user privacy by keeping data on-device, and dramatically cuts inference costs for high-volume lightweight tasks. Transformers.js v2 builds on ONNX Runtime Web 1.18 and provides pre-converted Hugging Face models that run via WebAssembly or WebGPU. This post shows exactly how to integrate it into a Next.js 15 application using React Server Components where possible and client-side dynamic imports where required.

Project Setup and Dependency Configuration

Start with the latest Next.js scaffolding:

 npx create-next-app@latest transformers-demo \
  --typescript --tailwind --eslint --app --yes
cd transformers-demo
npm install @xenova/transformers@2.17.0

The package size exceeds 40 MB before compression because it includes the ONNX Runtime Web runtime and tokenizer implementations. Never import it on the server. Create a dedicated client-only utility.

In next.config.mjs add the required experimental flags for WASM:

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    esmExternals: 'loose',
  },
  webpack(config) {
    config.resolve.alias = {
      ...config.resolve.alias,
      '@xenova/transformers': '@xenova/transformers',
    };
    return config;
  },
};
export default nextConfig;

Next.js 15 automatically handles the WASM files when placed inside the public folder or imported as static assets. The library downloads models from the Hugging Face Hub on first use and caches them in IndexedDB automatically.

Creating a Reusable Inference Hook

A custom React hook prevents multiple pipeline instantiations. Create hooks/usePipeline.ts:

'use client';
import { useState, useEffect, useRef, useCallback } from 'react';
import { pipeline, env } from '@xenova/transformers';

env.allowLocalModels = false;
env.backends.onnx.wasm.numThreads = 4;

type Task = 'sentiment-analysis' | 'translation' | 'feature-extraction' | 
            'zero-shot-classification' | 'image-classification';

export function usePipeline<T = any>(task: Task, model?: string) {
  const [result, setResult] = useState<T | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const pipelineRef = useRef<any>(null);

  const loadPipeline = useCallback(async () => {
    if (pipelineRef.current) return pipelineRef.current;
    
    setIsLoading(true);
    try {
      const pipe = await pipeline(
        task, 
        model || undefined,
        { 
          quantized: true,
          progress_callback: (data) => {
            if (data.status === 'download') {
              console.log(`Downloading ${data.file}: ${Math.round(data.progress)}%`);
            }
          }
        }
      );
      pipelineRef.current = pipe;
      return pipe;
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load model');
      throw err;
    } finally {
      setIsLoading(false);
    }
  }, [task, model]);

  const run = useCallback(async (input: any, options = {}) => {
    setIsLoading(true);
    setError(null);
    try {
      const pipe = await loadPipeline();
      const output = await pipe(input, options);
      setResult(output);
      return output;
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Inference failed';
      setError(message);
      throw err;
    } finally {
      setIsLoading(false);
    }
  }, [loadPipeline]);

  return { run, result, isLoading, error, pipelineRef };
}

This hook manages the singleton pattern for each task. The quantized: true flag uses 8-bit INT8 models by default, reducing memory footprint by roughly 4× compared with FP32.

Sentiment Analysis and Text Classification

The distilled BERT model fine-tuned on SST-2 provides excellent speed versus accuracy balance. Model size after quantization is 67 MB.

'use client';
import { usePipeline } from '@/hooks/usePipeline';

export default function SentimentDemo() {
  const { run, result, isLoading } = usePipeline('sentiment-analysis', 
    'Xenova/distilbert-base-uncased-finetuned-sst-2-english');

  const analyze = async () => {
    const text = "The new API design is both elegant and performant.";
    const output = await run(text);
    console.log(output); 
    // [{ label: 'POSITIVE', score: 0.998 }]
  };

  return (
    <button 
     
      disabled={isLoading}
      className="px-6 py-3 bg-violet-600 hover:bg-violet-700 text-white rounded-xl"
    >
      {isLoading ? 'Analyzing...' : 'Run Sentiment Analysis'}
    </button>
  );
}

Output always returns an array of objects with label and score. For multi-class models such as emotion detection, use Xenova/bart-large-mnli with the zero-shot pipeline instead.

Zero-Shot Classification for Flexible Labeling

Zero-shot models remove the need to fine-tune for every new category. The BART-large-mnli model (340 MB quantized) works reliably.

Typical call:

const classifier = await pipeline('zero-shot-classification');
const result = await classifier(
  "I love the new search experience", 
  ["positive feedback", "feature request", "complaint", "billing issue"]
);
console.log(result.labels[0]); // "positive feedback"
console.log(result.scores[0]); // 0.87

This pattern is useful for support ticket routing or content moderation where categories change frequently. The model performs surprisingly well on domain-specific text even without fine-tuning when candidate labels are descriptive.

Generating Text Embeddings for Semantic Search

Client-side embeddings enable small-scale semantic search without a vector database. The all-MiniLM-L6-v2 model (80 MB quantized) produces 384-dimensional vectors.

import { pipeline } from '@xenova/transformers';

async function generateEmbedding(text: string) {
  const extractor = await pipeline(
    'feature-extraction', 
    'Xenova/all-MiniLM-L6-v2'
  );
  
  const output = await extractor(text, {
    pooling: 'mean',
    normalize: true,
  });
  
  return Array.from(output.data);
}

// Cosine similarity helper
function cosineSimilarity(a: number[], b: number[]) {
  let dot = 0, normA = 0, normB = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }
  return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}

Store embeddings for 200–500 documents in memory or IndexedDB. For larger corpora, combine with a lightweight index such as usearch-wasm. This approach works well for personalized recommendation widgets or document search inside SaaS dashboards.

Multilingual Translation with Seamless Integration

Transformers.js v2 supports NLLB-200 distilled variants. The 600M distilled model offers good quality at 210 MB quantized.

const translator = await pipeline(
  'translation', 
  'Xenova/nllb-200-distilled-600M'
);

const result = await translator(
  "The quick brown fox jumps over the lazy dog.", 
  {
    src_lang: "eng_Latn",
    tgt_lang: "fra_Latn"
  }
);
// Returns array with translation_text property

Language codes follow the Flores-200 convention. The model supports 200+ languages. For production UIs, provide language auto-detection using the facebook/m2m100_418M model first, then translate.

Computer Vision Tasks in the Browser

Image classification works surprisingly well. MobileNet-v2 and EfficientNet variants run at interactive speeds on modern laptops.

const imageClassifier = await pipeline(
  'image-classification', 
  'Xenova/mobilenet_v2'
);

const img = document.createElement('img');
img.src = '/test-image.jpg';

const results = await imageClassifier(img, { topk: 5 });
// [{ label: 'tabby cat', score: 0.912 }, ...]

For object detection, use Xenova/yolos-tiny. The library automatically converts Canvas, Image, or Blob inputs. Combine with the browser's getUserMedia API to build real-time filters or quality control tools without sending images to a server.

WebGPU Acceleration and Backend Selection

ONNX Runtime Web 1.18 supports three execution providers: WASM, WebGL, and WebGPU. WebGPU provides 3–6× speedup on compatible devices.

Force WebGPU with:

env.backends.onnx.executionProviders = ['webgpu'];

// Or per-pipeline
const pipe = await pipeline('sentiment-analysis', 'model', {
  device: 'webgpu',
  dtype: 'fp16'
});

Not all models have fp16 weights. When WebGPU is unavailable, the library gracefully falls back to WebGL then WASM. Always detect support with if (navigator.gpu) { ... } and provide user feedback. On an M3 MacBook Pro, WebGPU inference for all-MiniLM-L6-v2 completes in 18–35 ms after initial compilation.

Memory Management and Model Lifecycle

Browser memory is limited. A single 1.5B parameter model can consume over 3 GB. Strategies that work:

  • Dispose pipelines explicitly with pipe.dispose() when no longer needed.
  • Use the smallest sufficient model for each task. Prefer distilled or quantized variants.
  • Lazy-load models behind user gestures or route-based dynamic imports.
  • Share a single embedding model across multiple features via a React Context provider.

Monitor usage with the Performance tab in Chrome DevTools. The performance.memory API (Chrome only) helps track JS heap size during development.

Production Deployment Considerations on Vercel and Cloudflare

Both Vercel and Cloudflare Pages serve the required WASM and model files without extra configuration. However, first-load model download can exceed 150 MB. Mitigate this by:

  1. Pre-warming popular models during build by running a small script that triggers downloads and copying the IndexedDB export if possible.
  2. Using Cloudflare's Cache Everything rule for the Hugging Face CDN domains.
  3. Implementing a service worker to cache model files with the Cache API for offline use.

Bundle size remains acceptable because the main @xenova/transformers package is dynamically imported. A typical Next.js app with three pipelines stays under 280 KB gzipped for the JS payload.

Combining Client and Server Inference Intelligently

Not every task belongs in the browser. A practical pattern routes requests as follows:

  • Sentiment, toxicity, language detection → browser
  • Complex summarization or 70B-scale generation → serverless API
  • High-accuracy medical or legal classification → server with GPU

Use a simple feature flag stored in localStorage or a cookie to toggle between runtimes during A/B testing. This hybrid approach delivers the best user experience while controlling cost and accuracy.

Security and Trust Boundaries

Client-side models can be inspected and modified by technically sophisticated users. Never use browser inference for:

  • Anti-cheat systems in games
  • Financial fraud detection that affects user balances
  • Content moderation decisions that result in permanent bans without server review

Always treat the client result as a hint and validate critical decisions server-side. The models themselves are not confidential; they are public weights. If your application deals with sensitive personal data, the on-device nature actually improves compliance with GDPR and CCPA because data never leaves the device.

Real-World Performance Numbers from Standard Hardware

On a 2023 MacBook Air M2 with 16 GB RAM using WebGPU:

  • all-MiniLM-L6-v2 embedding: 22 ms average after warm-up
  • distilbert sentiment: 14 ms
  • NLLB-200 600M translation: 380 ms for 28-token English to Spanish sentence
  • MobileNet-v2 image classification: 28 ms

Initial model load from cache takes 80–400 ms depending on size. Cold start from CDN ranges from 1.8 s (67 MB) to 14 s (340 MB) on a fast connection. These numbers make interactive experiences possible but require careful UI design with skeleton states and progressive enhancement.

Building a Complete Review Analysis Dashboard

Combine multiple pipelines into one component that analyzes product reviews:

function ReviewAnalyzer() {
  const sentiment = usePipeline('sentiment-analysis');
  const embedding = usePipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
  const topics = usePipeline('zero-shot-classification');

  const analyzeReview = async (text: string) => {
    const [sent, emb, topic] = await Promise.all([
      sentiment.run(text),
      embedding.run(text),
      topics.run(text, {
        candidate_labels: ['ux', 'performance', 'pricing', 'support']
      })
    ]);
    
    return {
      sentiment: sent[0],
      embedding: emb,
      primaryTopic: topic.labels[0]
    };
  };

  // Render results with confidence gauges using Recharts or custom SVG
}

This single function call pattern reduces total inference time by running pipelines concurrently where possible. The resulting dashboard works completely offline after the initial model cache is populated.

Observability and Debugging

Wrap inference calls with timing:

const start = performance.now();
const result = await pipe(input);
const duration = performance.now() - start;
console.log(`Inference took ${duration.toFixed(1)} ms`);

Log model loading progress to help users on slow connections. Expose a small diagnostics panel in staging environments that shows current execution provider, available threads, and memory usage. This data helps diagnose why inference might be slower on certain devices.

Future Roadmap and Model Updates

Transformers.js tracks Hugging Face closely. New models appear weekly. To update a model, simply change the model ID string. The library will download the new files on next run. For production applications, pin specific revisions using the full commit hash from the Hub to guarantee reproducibility.

WebNN support is landing in ONNX Runtime Web 1.19 and will further improve performance on Windows and Android devices with NPU hardware. Expect another 30-50% latency reduction on compatible silicon.

The combination of Next.js 15 streaming capabilities, React 19 concurrent features, and Transformers.js v2 creates new classes of applications that previously required heavy backend infrastructure. Features that once cost thousands of dollars per month in API fees can now run at essentially zero marginal cost while delivering sub-50 ms interactions.

Start small. Add one pipeline to an existing feature—perhaps sentiment analysis on user feedback or automatic language detection for your documentation search. Measure the impact on engagement and infrastructure cost, then expand. The tooling has reached production readiness for many real-world workloads.

Keep reading

Related Articles