MSMuhammad Shahid

Engineering notes

Building a Semantic Search Engine with Next.js and Transformers.js

By Muhammad Shahid · · 20 min read

Quick answer

To build semantic search in Next.js with Transformers.js, embed your documents once at build time with a small model such as all-MiniLM-L6-v2 and ship the vectors as a static JSON file. In the browser, a Web Worker loads the same model with Transformers.js, embeds only the visitor's query and ranks documents by cosine similarity, with keyword (BM25) results while the model downloads. On this site's 67 tools it put the right tool first for 25 of 30 plain-English questions against 16 for keyword search, with searches taking 9 to 41 ms and no server.

Key facts
StackNext.js 15 static export, Transformers.js 4, all-MiniLM-L6-v2 (q8), a Web Worker
AccuracyRight tool first: semantic 25/30, keyword 16/30, equal-weight hybrid 20/30
SpeedFirst result 0.26 s, model ready 8.2 s (23 MB) on the first visit, 0.58 s from cache; 9 to 41 ms per search
Index67 documents, int8 vectors: 48 KB, 27 KB gzipped
LanguagesSpanish questions: a multilingual model put the right tool in the top 3 for 10/10, the English model 5/10

A search box that understands "make my pdf smaller for email" and finds the Compress PDF tool, without a search server, an API key or a per-query bill: that is what semantic search in the browser gives you. This tutorial builds it with Next.js and Transformers.js, using the 67 free tools of this site as the documents, and measures it rather than assuming: how often the right tool comes first compared with keyword search, whether mixing the two helps, how it handles questions in another language, and how long it takes in a real browser. All code is complete, type-checked and built as a Next.js static export; the accuracy numbers come from real embeddings in Node.js and the timings from Google Chrome driven by Playwright.

What is semantic search, and why run it in the browser?

Semantic search ranks documents by meaning instead of shared words. A small language model turns each document and each query into a vector, a list of numbers, so that texts with similar meaning get similar vectors; the closest vectors are the best matches. Keyword search can only match "compress" if the visitor types "compress"; semantic search also matches "smaller", "shrink" and "reduce the size". Running it in the browser with Transformers.js means no search server to host, no cost per query, and nothing the visitor types leaves their device. The price is a one-time model download, which this design hides behind instant keyword results.

The design

Design: at build time a Node script embeds 67 documents with all-MiniLM-L6-v2 through Transformers.js and writes search-index.json with int8 vectors, 48 KB or 27 KB gzipped; in the browser a Next.js page talks to a Web Worker that answers with BM25 keyword search at once, downloads the 23 MB model once from Hugging Face, then embeds the query and compares it with the 67 vectors in 9 to 41 ms
Documents are embedded once at build time; only the query is embedded in the browser.

Two decisions make it fast. First, the documents' vectors are computed once at build time and shipped as a small static file, so the browser only ever embeds the query. Second, all model work happens in a Web Worker, so loading and embedding never block typing, and the worker answers with keyword search until the model is ready.

What do you need?

ToolVersion usedWhy
Next.js15, static exportThe page; any static host serves it
@huggingface/transformers4Runs the embedding model in Node and in the browser
all-MiniLM-L6-v2q8 (8-bit) weights384-number vectors, about 23 MB to download
TypeScript6Next.js 15 needs TypeScript 6; it does not support TypeScript 7 yet
tsxanyRuns the build-time indexing script

Step 1: Set up the project

npx create-next-app@15 tool-search --ts --app --no-tailwind --no-eslint && cd tool-search
npm install @huggingface/transformers
npm install -D tsx
/** @type {import('next').NextConfig} */
export default { output: "export" };

output: "export" makes next build write plain HTML, JavaScript and the index file to out/, so the search works on any static host with no server at all.

Step 2: The search code

// Search logic shared by the build script, the browser worker and the tests. No dependencies.

export interface Doc { slug: string; href: string; name: string; text: string }
export interface SearchIndex { model: string; dims: number; docs: Doc[]; vectors: string } // vectors: base64 int8, docs x dims

// ---- Semantic: int8 vectors (normalised floats x 127), compared with a dot product
export function quantize(v: Float32Array): Int8Array {
  return Int8Array.from(v, (x) => Math.max(-127, Math.min(127, Math.round(x * 127))));
}
export function decodeVectors(b64: string): Int8Array {
  const bin = atob(b64);
  return Int8Array.from(bin, (c) => (c.charCodeAt(0) << 24) >> 24);
}
export function encodeVectors(all: Int8Array): string {
  let s = "";
  for (const x of all) s += String.fromCharCode(x & 255);
  return btoa(s);
}
export function semanticScores(query: Float32Array, vectors: Int8Array, dims: number): number[] {
  const n = vectors.length / dims;
  return Array.from({ length: n }, (_, d) => {
    let dot = 0;
    for (let i = 0; i < dims; i++) dot += query[i] * vectors[d * dims + i];
    return dot / 127; // cosine similarity, since both sides are normalised
  });
}

// ---- Keyword: BM25 over name + text
const tokenize = (s: string) => s.toLowerCase().normalize("NFKC").match(/[\p{L}\p{N}]+/gu) ?? [];
export function bm25Scorer(docs: Doc[], k1 = 1.2, b = 0.75) {
  const toks = docs.map((d) => tokenize(d.name + " " + d.name + " " + d.text)); // the name counts twice
  const avg = toks.reduce((n, t) => n + t.length, 0) / toks.length;
  const df = new Map<string, number>();
  for (const t of toks) for (const w of new Set(t)) df.set(w, (df.get(w) ?? 0) + 1);
  return (query: string) => {
    const q = [...new Set(tokenize(query))];
    return toks.map((t) => {
      let score = 0;
      for (const w of q) {
        const f = t.filter((x) => x === w).length;
        if (!f) continue;
        const idf = Math.log(1 + (docs.length - df.get(w)! + 0.5) / (df.get(w)! + 0.5));
        score += (idf * f * (k1 + 1)) / (f + k1 * (1 - b + (b * t.length) / avg));
      }
      return score;
    });
  };
}

// ---- Hybrid: reciprocal rank fusion, which needs only the two rankings, not comparable scores
export const rank = (scores: number[]) => scores.map((s, i) => [s, i] as const).sort((a, b) => b[0] - a[0]).map(([, i]) => i);
// weights let the better signal count more; equal weights are the classic RRF.
export function rrf(rankings: number[][], weights = rankings.map(() => 1), k = 60): number[] {
  const total = new Map<number, number>();
  rankings.forEach((r, j) => r.forEach((doc, pos) => total.set(doc, (total.get(doc) ?? 0) + weights[j] / (k + pos + 1))));
  return [...total.entries()].sort((a, b) => b[1] - a[1]).map(([doc]) => doc);
}

This file has no dependencies and runs in Node, the browser and the tests alike. Vectors are stored as int8: each number is multiplied by 127 and rounded, which makes the index four times smaller than 32-bit floats. The test below checks what that costs: for all 30 questions the top result was the same as with full-precision vectors. bm25Scorer is classic keyword ranking, used while the model loads. rrf is reciprocal rank fusion, the usual way to mix two rankings, kept here because the test measures whether mixing actually helps.

Step 3: Embed the documents at build time

// Build time: embed every document once and ship the vectors as a small static file.
import { readFileSync, writeFileSync } from "node:fs";
import { pipeline } from "@huggingface/transformers";
import { encodeVectors, quantize, type Doc, type SearchIndex } from "../lib/search";

export const MODEL = "Xenova/all-MiniLM-L6-v2";
const docs: Doc[] = JSON.parse(readFileSync("corpus.json", "utf8")).map(({ slug, href, name, text }: Doc) => ({ slug, href, name, text }));
const embed = await pipeline("feature-extraction", MODEL, { dtype: "q8" }); // same model and precision as the browser
const all = new Int8Array(docs.length * 384);
for (const [i, d] of docs.entries()) {
  const out = await embed(d.name + ". " + d.text, { pooling: "mean", normalize: true });
  all.set(quantize(out.data as Float32Array), i * 384);
}
const index: SearchIndex = { model: MODEL, dims: 384, docs, vectors: encodeVectors(all) };
writeFileSync("public/search-index.json", JSON.stringify(index));
console.log("indexed " + docs.length + " docs, " + JSON.stringify(index).length + " bytes");

The script embeds each document's name and description with the same model and the same 8-bit weights the browser will use, which matters: vectors from different models, or even different precisions, are not comparable. Run it before next build (for example as a prebuild script) so the index always matches the content. For 67 documents it takes a few seconds and writes 48 KB, 27 KB gzipped.

Step 4: The Web Worker

// Runs in a Web Worker: downloading the model and embedding never block typing.
// Keyword (BM25) results answer at once; semantic results take over as soon as the model is ready.
import { pipeline, type FeatureExtractionPipeline } from "@huggingface/transformers";
import { bm25Scorer, decodeVectors, rank, semanticScores, type SearchIndex } from "../../lib/search";

const indexReady = fetch("/search-index.json").then((r) => r.json() as Promise<SearchIndex>);
const keyword = indexReady.then((index) => ({ index, bm25: bm25Scorer(index.docs) }));
let model: FeatureExtractionPipeline | null = null;

indexReady.then(async (index) => {
  const t0 = performance.now();
  model = await pipeline("feature-extraction", index.model, { dtype: "q8" }); // cached by the browser after the first visit
  self.postMessage({ modelReady: Math.round(performance.now() - t0) });
});
const vectors = indexReady.then((index) => decodeVectors(index.vectors));

self.onmessage = async (e: MessageEvent<{ id: number; query: string }>) => {
  const { id, query } = e.data;
  const { index, bm25 } = await keyword;
  const t0 = performance.now();
  let scores: number[];
  let mode: "semantic" | "keyword";
  if (model) {
    const q = (await model(query, { pooling: "mean", normalize: true })).data as Float32Array;
    scores = semanticScores(q, await vectors, index.dims);
    mode = "semantic";
  } else {
    scores = bm25(query); // the model is still downloading: answer with keywords instead of waiting
    mode = "keyword";
  }
  const order = rank(scores).slice(0, 5);
  const results = order.filter((i) => scores[i] > 0).map((i) => ({ ...index.docs[i], score: Number(scores[i].toFixed(2)) }));
  self.postMessage({ id, mode, results, ms: Math.round(performance.now() - t0) });
};

The worker fetches the index straight away and builds the keyword scorer, so the first search can be answered before the model exists. The model download starts in parallel; Transformers.js stores the files in the browser's Cache Storage, so the second visit loads them from disk. Every message carries an id, and the worker reports which mode answered, so the page can say "keyword" or "semantic". Results with a score of 0 are dropped, so a keyword search with no matches shows nothing rather than random tools.

Step 5: The search page

"use client";
import { useEffect, useRef, useState } from "react";
import type { Doc } from "../../lib/search";

type Result = Doc & { score: number };

export default function SearchPage() {
  const worker = useRef<Worker | null>(null);
  const latest = useRef(0);
  const [modelMs, setModelMs] = useState<number | null>(null);
  const [mode, setMode] = useState("");
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<Result[]>([]);
  const [ms, setMs] = useState<number | null>(null);

  useEffect(() => {
    const w = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
    w.onmessage = (e) => {
      if ("modelReady" in e.data) return setModelMs(e.data.modelReady);
      if (e.data.id !== latest.current) return; // ignore answers to older keystrokes
      setResults(e.data.results);
      setMs(e.data.ms);
      setMode(e.data.mode);
    };
    worker.current = w;
    return () => w.terminate();
  }, []);

  useEffect(() => {
    if (query.trim().length < 3) return setResults([]);
    const id = ++latest.current;
    const t = setTimeout(() => worker.current?.postMessage({ id, query }), 150); // debounce typing
    return () => clearTimeout(t);
  }, [query]);

  return (
    <main>
      <h1>Find a tool</h1>
      <input
        aria-label="Describe what you want to do"
        placeholder="e.g. make my pdf smaller"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        style={{ width: "100%", boxSizing: "border-box", fontSize: 18, padding: 10 }}
      />
      <p role="status">
        {ms !== null ? mode + " search, " + ms + " ms, on your device. " : ""}
        {modelMs === null ? "Smart search is loading; keyword results until then." : "Smart search ready."}
      </p>
      <ol>
        {results.map((r) => (
          <li key={r.slug}>
            <a href={r.href}>{r.name}</a> <small>({r.score})</small>
            <div>{r.text}</div>
          </li>
        ))}
      </ol>
    </main>
  );
}

The page debounces typing by 150 ms and ignores any answer that is not for the latest query, so a slow answer to "mak" cannot overwrite the answer to "make my pdf". new Worker(new URL("./worker.ts", import.meta.url)) is the pattern Next.js bundles into a separate worker file. The status line is an ARIA live region, so screen readers hear when results change.

How accurate is it?

// How people actually ask, labelled with the tool that answers. None of them uses the tool's name.
export const queries: [string, string][] = [
  ["make my pdf file smaller for email", "compress-pdf"],
  ["join two pdfs into one", "merge-pdf"],
  ["turn a photo of a page into text I can copy", "image-to-text"],
  ["how long is my essay", "word-counter"],
  ["work out how old I am", "age-calculator"],
  ["shrink a picture without losing quality", "image-compressor"],
  // ...27 more, plus 10 Spanish questions and 10 short keyword searches
];
// Measures keyword, semantic and hybrid search on the labelled questions, and an English-only
// versus a multilingual model on Spanish questions. Real embeddings, run in Node.
import { readFileSync } from "node:fs";
import { pipeline } from "@huggingface/transformers";
import { bm25Scorer, decodeVectors, rank, rrf, semanticScores, type SearchIndex } from "../lib/search";
import { keywords, queries, spanish } from "./queries";

const index: SearchIndex = JSON.parse(readFileSync("public/search-index.json", "utf8"));
const vectors = decodeVectors(index.vectors);
const slugs = index.docs.map((d) => d.slug);
const bm25 = bm25Scorer(index.docs);

function report(label: string, rankings: number[][], wanted: string[]) {
  let hit1 = 0, hit3 = 0, mrr = 0;
  rankings.forEach((r, i) => {
    const pos = r.map((d) => slugs[d]).indexOf(wanted[i]);
    if (pos === 0) hit1++;
    if (pos >= 0 && pos < 3) hit3++;
    if (pos >= 0) mrr += 1 / (pos + 1);
  });
  const n = rankings.length;
  console.log(label.padEnd(34) + "top 1: " + String(hit1).padStart(2) + "/" + n + "   top 3: " + String(hit3).padStart(2) + "/" + n + "   MRR " + (mrr / n).toFixed(2));
}

const embed = await pipeline("feature-extraction", index.model, { dtype: "q8" });
// The query stays in float32; only the stored document vectors are int8.
const qv = async (q: string) => (await embed(q, { pooling: "mean", normalize: true })).data as Float32Array;

const kw = queries.map(([q]) => rank(bm25(q)));
const sem = await Promise.all(queries.map(async ([q]) => rank(semanticScores(await qv(q), vectors, index.dims))));
const hyb = kw.map((k, i) => rrf([k, sem[i]]));
console.log(queries.length + " English questions, " + index.docs.length + " tools");
report("keyword (BM25)", kw, queries.map((q) => q[1]));
report("semantic (MiniLM-L6, int8 docs)", sem, queries.map((q) => q[1]));
report("hybrid, equal weights (RRF)", hyb, queries.map((q) => q[1]));
for (const w of [2, 3, 5]) report("hybrid, semantic weighted x" + w, kw.map((k, i) => rrf([k, sem[i]], [1, w])), queries.map((q) => q[1]));

// Short keyword searches
const kKw = keywords.map(([q]) => rank(bm25(q)));
const kSem = await Promise.all(keywords.map(async ([q]) => rank(semanticScores(await qv(q), vectors, index.dims))));
console.log(keywords.length + " short keyword searches");
report("keyword (BM25)", kKw, keywords.map((q) => q[1]));
report("semantic (MiniLM-L6, int8 docs)", kSem, keywords.map((q) => q[1]));
report("hybrid, equal weights (RRF)", kKw.map((k, i) => rrf([k, kSem[i]])), keywords.map((q) => q[1]));
for (const w of [2, 3, 5]) report("hybrid, semantic weighted x" + w, kKw.map((k, i) => rrf([k, kSem[i]], [1, w])), keywords.map((q) => q[1]));

// Does int8 storage change the ranking? Compare with full-precision document vectors.
let same = 0;
const full = await Promise.all(index.docs.map(async (d) => (await embed(d.name + ". " + d.text, { pooling: "mean", normalize: true })).data as Float32Array));
for (const [i, [q]] of queries.entries()) {
  const v = await qv(q);
  const exact = rank(full.map((f) => f.reduce((s, x, j) => s + x * v[j], 0)));
  if (exact[0] === sem[i][0]) same++;
}
console.log("int8 vs float32 document vectors: same top result for " + same + "/" + queries.length + " questions");

// Spanish questions against English documents
console.log(spanish.length + " Spanish questions, English documents");
report("keyword (BM25)", spanish.map(([q]) => rank(bm25(q))), spanish.map((q) => q[1]));
report("semantic, English model", await Promise.all(spanish.map(async ([q]) => rank(semanticScores(await qv(q), vectors, index.dims)))), spanish.map((q) => q[1]));
const multi = await pipeline("feature-extraction", "Xenova/paraphrase-multilingual-MiniLM-L12-v2", { dtype: "q8" });
const mDocs = await Promise.all(index.docs.map(async (d) => (await multi(d.name + ". " + d.text, { pooling: "mean", normalize: true })).data as Float32Array));
const mRank = await Promise.all(spanish.map(async ([q]) => {
  const v = (await multi(q, { pooling: "mean", normalize: true })).data as Float32Array;
  return rank(mDocs.map((d) => d.reduce((s, x, j) => s + x * v[j], 0)));
}));
report("semantic, multilingual model", mRank, spanish.map((q) => q[1]));
30 English questions, 67 tools
keyword (BM25)                    top 1: 16/30   top 3: 20/30   MRR 0.62
semantic (MiniLM-L6, int8 docs)   top 1: 25/30   top 3: 30/30   MRR 0.91
hybrid, equal weights (RRF)       top 1: 20/30   top 3: 24/30   MRR 0.76
hybrid, semantic weighted x2      top 1: 20/30   top 3: 26/30   MRR 0.79
hybrid, semantic weighted x3      top 1: 22/30   top 3: 27/30   MRR 0.84
hybrid, semantic weighted x5      top 1: 24/30   top 3: 29/30   MRR 0.88
10 short keyword searches
keyword (BM25)                    top 1:  8/10   top 3:  9/10   MRR 0.85
semantic (MiniLM-L6, int8 docs)   top 1:  9/10   top 3: 10/10   MRR 0.95
hybrid, equal weights (RRF)       top 1:  8/10   top 3:  9/10   MRR 0.86
hybrid, semantic weighted x2      top 1:  8/10   top 3:  9/10   MRR 0.87
hybrid, semantic weighted x3      top 1:  8/10   top 3: 10/10   MRR 0.88
hybrid, semantic weighted x5      top 1:  9/10   top 3: 10/10   MRR 0.95
int8 vs float32 document vectors: same top result for 30/30 questions
10 Spanish questions, English documents
keyword (BM25)                    top 1:  2/10   top 3:  3/10   MRR 0.29
semantic, English model           top 1:  2/10   top 3:  5/10   MRR 0.34
semantic, multilingual model      top 1:  6/10   top 3: 10/10   MRR 0.80
Bar chart of top-1 accuracy: on 30 plain-English questions keyword search 53%, semantic 83%, equal-weight hybrid 67%; on 10 short keyword searches keyword 80%, semantic 90%, hybrid 80%; on 10 Spanish questions against English documents the English model 20% and a multilingual model 60%
Right tool in first place, on questions labelled by hand.

The questions were written the way people ask, without the tool's name: "how long is my essay", "erase what is behind a person in a photo". Semantic search put the right tool first for 25 of 30 and in the top three for all 30; keyword search managed 16 first places. On short keyword searches like "jwt" or "bmi", where keyword search should shine, semantic search still came out slightly ahead, 9 against 8 out of 10. The small model handles abbreviations better than you might expect because the documents spell them out.

Hybrid search: when it helps and when it hurts

Hybrid search, mixing keyword and semantic rankings, is often recommended as the safe default, so the test measured it. With equal weights it made results worse: 20 first places against semantic's 25, because on plain-language questions the keyword ranking is mostly noise and fusion gives it as much say as the good ranking. Giving semantic five times the weight recovered to 24, still not above semantic alone. Hybrid search does pay off when queries contain rare exact terms the model has never seen, such as product codes, error codes or people's names; on a set like this one, it did not. Measure on your own questions before you choose. This page uses semantic search once the model is loaded, and keyword search only while it loads.

Other languages

all-MiniLM-L6-v2 was trained on English. Asked in Spanish against English documents, it put the right tool first for only 2 of 10 questions. The multilingual model paraphrase-multilingual-MiniLM-L12-v2 got 6 first places and all 10 in the top three, because it maps sentences with the same meaning in different languages to nearby vectors. It is a larger download, so use it when your visitors search in languages other than your documents', and embed the documents with the same model.

How fast is it?

first visit: first result after 262 ms (keyword search: Compress PDF); smart search ready after 8248 ms; model downloaded 23.0 MB; sideways overflow 0px
  join two pdfs into one -> Merge PDF (41 ms)
  erase what is behind a person in a photo -> Background remover (16 ms)
  how far does a car go before it stops -> Stopping distance calculator (20 ms)
  unique id for a database row -> UUID generator (9 ms)
second visit (browser cache): first result after 573 ms (semantic search: Compress PDF); smart search ready after 578 ms; model downloaded 0.0 MB; sideways overflow 0px
  join two pdfs into one -> Merge PDF (10 ms)
  erase what is behind a person in a photo -> Background remover (12 ms)
  how far does a car go before it stops -> Stopping distance calculator (24 ms)
  unique id for a database row -> UUID generator (12 ms)
Timeline measured in Chrome: on the first visit a keyword result after 0.26 seconds and semantic search ready after 8.2 seconds while a 23 MB model downloads; on the second visit semantic search is ready after 0.58 seconds from the browser cache; each semantic search takes 9 to 41 milliseconds
The first visit pays for the model download once; after that, search is instant.

On the first visit the first result appeared after 0.26 seconds, from keyword search, while the 23 MB model downloaded; semantic search was ready after 8.2 seconds. On the second visit the model came from the browser cache and semantic search was ready in 0.58 seconds. Each semantic search took 9 to 41 ms. These timings are from one laptop on a home connection, so expect a slower first visit on a phone with mobile data; the keyword fallback is what keeps the box useful in the meantime.

Making it smaller and faster

  • Load the model on intent: start the download when the visitor focuses the search box, not on every page view, to save data for people who never search.
  • Keep the index lean: int8 vectors cost 384 bytes per document; for a few thousand documents that is still around a megabyte.
  • Self-host the model files on your own CDN if you do not want visitors' browsers to fetch them from Hugging Face.
  • Use WebGPU where available for larger models; for a model this small, the CPU is already fast enough.

Common mistakes and how to fix them

MistakeWhat happensFix
Different models or precisions for documents and queriesScores are meaningless; results look randomSame model and dtype at build time and in the browser
Embedding every document in the browserSlow first search, wasted batteryEmbed documents at build time, ship the vectors
Running the model on the main threadTyping freezes while the model loadsDo all model work in a Web Worker
Waiting for the model before showing anythingAn empty box for seconds on a slow phoneAnswer with keyword search until the model is ready
Assuming hybrid search is always betterWorse results on plain-language queriesMeasure both on your own questions
An English model for other languagesNon-English queries missUse a multilingual model for both sides
Stale index after content changesNew pages never show upRebuild the index in prebuild

Limitations

The test set is small: 30 English questions, 10 short searches and 10 Spanish questions, written and labelled by one person, so read the numbers as a comparison between methods on this site, not as general accuracy. Client-side search suits collections from dozens to a few thousand documents; beyond that the index and the scoring loop grow, and a vector database becomes the better tool. The first visit costs a 23 MB download, which is too much for some audiences on mobile data. And a small model sometimes ranks near-misses close together, so show three to five results, not one.

When to use a server instead

Move search to a server when the collection is large, private, or changes every minute, or when you need filters, permissions per user and analytics on queries. Then the same idea works with a vector database: see the RAG pipeline with pgvector and the MongoDB Atlas vs pgvector comparison. The same small embedding model also powers the semantic cache in the guide to cutting LLM costs with Redis. You can see the documents this article searched on the free tools page.

Frequently asked questions

Can I run semantic search entirely in the browser?

Yes. Transformers.js runs embedding models such as all-MiniLM-L6-v2 in the browser, so you can embed the query on the device and compare it with document vectors shipped as a static file, with no server.

How big is the model download?

all-MiniLM-L6-v2 with 8-bit weights downloaded 23 MB in the test. The browser caches it, so the second visit loaded it in 0.58 seconds.

Should I embed documents in the browser?

No. Embed them once at build time with the same model and precision, and ship the vectors. The browser then only embeds the query.

How fast is client-side semantic search?

In the test each search took 9 to 41 ms for 67 documents on a laptop, running in a Web Worker so typing never stutters.

Is semantic search better than keyword search?

On plain-language questions, much better: 25 of 30 right first against 16 for BM25 keyword search in the test. On short keyword searches it was slightly better too.

Does hybrid search always improve results?

No. In the test an equal-weight mix of keyword and semantic rankings scored 20 of 30 against 25 for semantic alone. Hybrid helps most with rare exact terms like codes and names.

How do I use Transformers.js in Next.js?

Load it inside a Web Worker created with new Worker(new URL("./worker.ts", import.meta.url)), call pipeline("feature-extraction", model) there, and post queries and results as messages.

Does semantic search work in other languages?

With a multilingual model, yes. For Spanish questions against English documents, paraphrase-multilingual-MiniLM-L12-v2 found the right tool in the top three for 10 of 10, the English-only model for 5.

Do int8 vectors lose accuracy?

Barely. In the test the top result with int8 document vectors matched full-precision vectors for all 30 questions, at a quarter of the size.

What should the search show while the model downloads?

Keyword results. The test page answered with BM25 after 0.26 seconds and switched to semantic search when the model was ready.

Does client-side search send queries to a server?

No. The query is embedded and compared on the device. Only the model files are downloaded, once.

When should I use a vector database instead?

When the collection is large, private or changing constantly, or when you need per-user permissions and filters. Client-side search suits dozens to a few thousand public documents.

Sources

Free apps from the author of this guide