How to add search to a static site

A static site has no server to run a query, so the search index has to be a file — built from your pages after every build and searched in the browser, or kept by someone else's service. Four ways to do it, what each one needs, and the three mistakes that leave pages out of the results.

Your site is a folder of HTML files on a static host. Visitors want a search box, and the tutorials you find assume a database or a server that can answer ?q= — which your host does not have.

The usual answer is to build a search index from your finished pages at build time, publish it as static files next to them, and run the search in the visitor's browser. Pagefind does exactly that for any folder of HTML, with no server component. Lunr and Fuse.js do the same job with an index you build yourself. If you would rather not ship an index at all, a hosted service such as Algolia DocSearch keeps it for you, and Google Programmable Search uses Google's own index of your site.

The 30-second version

Approach Where the index lives What it needs from you Catch
Pagefind pagefind/ folder in your build output one command after every build indexes the HTML files, not what JavaScript adds later
Lunr or Fuse.js a JSON file you generate a script that collects your content the browser downloads the whole index
Algolia DocSearch Algolia's servers an application, then their crawler free only for public technical docs and technical blogs
Google Programmable Search Google's index a search engine created in Google's console only pages Google has indexed; ads on the free tier

If you are unsure, start with Pagefind: it reads the output of any generator, and removing it later is one build step and one snippet.

Why "search" means "a file" on a static host

A static host answers every request with a file that already exists. There is no process waiting to read ?q=widgets, run a query and render a results page. So a search box on a static site has three places to send that query:

  1. To a file in your own site. An index built at build time, downloaded by the browser, searched with JavaScript. Pagefind, Lunr and Fuse.js work this way.
  2. To someone else's server. A hosted search service that crawled or received your content. Algolia is the common one.
  3. To Google. A Programmable Search Engine restricted to your domain.

The first keeps everything on your host. The second and third add a third party and a script from them on every page that has the box.

Option 1: Pagefind

Pagefind runs after your static generator and writes a search bundle into the generated site. Point it at the folder your generator outputs:

BASH
npx -y pagefind --site public

Replace public with the folder your generator writes. The bundle lands in a pagefind/ subfolder of it by default. Then put the search UI on a page:

HTML
<link href="/pagefind/pagefind-component-ui.css" rel="stylesheet">
<script src="/pagefind/pagefind-component-ui.js" type="module"></script>

<pagefind-modal-trigger></pagefind-modal-trigger>
<pagefind-modal></pagefind-modal>

Those two files do not exist in your source. Pagefind creates them when it indexes the site, which is why the command has to run after the build and before you upload, every time. Install it in the project with npm i -D pagefind, then chain it onto your build script — here for a generator that writes to public:

JSON
{
  "scripts": {
    "build": "your-generator-build && pagefind --site public"
  }
}

The index is split into chunks, so a browser downloads only the parts a query needs. Pagefind's own figure is a full-text search on a 10,000-page site with a total network payload under 300 kB, library included. That is their measurement, not ours.

Some frameworks ship it already. Starlight, Astro's documentation theme, uses Pagefind by default, so there is nothing to add there.

What Pagefind reads, and what it skips

By default it starts from <body> and skips <nav> and <footer>. Two attributes change that:

  • data-pagefind-ignore on an element keeps its text out of the index — useful for a sidebar or a "related posts" block that would otherwise match every query.
  • data-pagefind-body marks the part of a page to index. Read the warning before using it: if it appears on any page of your site, every page without it stops being indexed.

By default it reads only files matching **/*.{html}; the glob option changes which HTML files it picks up. Content that is not an HTML file — a JSON feed, a PDF's text — can be added through the Node API's addCustomRecord.

Option 2: Lunr or Fuse.js with your own index

Before Pagefind, the common approach was a JSON file of every page's title and text, generated by your build, plus a small library that searches it in the browser. Lunr is the full-text one; Fuse.js calls itself a "lightweight fuzzy-search library, with zero dependencies".

Lunr can build its index in the browser, but its documentation says that for large numbers of documents this takes time and recommends pre-building it in Node and serving the serialised result:

JS
// build-index.cjs — run after your generator
const lunr = require("lunr");
const pages = require("./pages.json"); // [{ url, title, body }, …] from your generator

const idx = lunr(function () {
  this.ref("url");
  this.field("title");
  this.field("body");
  pages.forEach((page) => this.add(page));
});

process.stdout.write(JSON.stringify(idx));

Run it as node build-index.cjs > public/search-index.json, so the index is published with your pages. Then load Lunr and the index in the page:

HTML
<script src="https://unpkg.com/lunr@2.3.9/lunr.min.js"></script>
<script type="module">
  const data = await fetch("/search-index.json").then((r) => r.json());
  const idx = lunr.Index.load(data);
  const results = idx.search("widgets");
</script>

Making the page URL the ref means each result can link straight to its page. The index does not keep titles or text, so to show a title in the results, publish a small { url: title } map alongside it.

The catch is in that fetch. The browser downloads the entire index before it can answer one query, and the index grows with every page you add. Pagefind's chunked index avoids exactly this. What you get in exchange is simplicity when your generator already has the content as data: a JSON file in, a JSON index out. (Pagefind can take source data too, through addCustomRecord.) MkDocs' built-in search plugin uses Lunr.

Option 3: a hosted index — Algolia DocSearch

A hosted service keeps the index on its servers and answers queries over an API, so nothing grows in your build. For documentation the usual choice is Algolia DocSearch, which crawls your site for you.

It is free, but only for some sites. In Algolia's words, the program is for "public technical documentation and technical blogs", applications are usually turned down when a site is "not production ready or [has] non-technical content", and you have seven days after approval to verify you own the domain. A shop, a portfolio or a club's website is unlikely to qualify for that program.

Option 4: Google Programmable Search Engine

Google lets you create a search engine limited to your own site and paste its element into a page. There is no build step. Two things decide whether it is any good for you.

It only knows the pages Google knows. Google's help is explicit: for your site's contents to appear in results, they need to be in the Google index, and indexing "may not happen immediately". A page published this morning is not searchable until Google has crawled it. A page marked noindex is kept out of Google's index, so it never is.

A default *.dropto.live address, for instance, sends X-Robots-Tag: noindex on every response, so this option returns nothing there until the site is on its own domain. Why a site isn't showing up on Google shows how to check what your host sends.

The free element shows ads. The Standard Search Element is free and carries them. The ad-free options are the Non-profit element, for non-profits only, and a paid element.

Wrap the search form in <search>. It defines a search landmark, which removes the need for role="search" on the form, and it has worked across browsers since October 2023. Results belong in the page's main content, not inside <search>. Because nothing on a static host answers ?q=, the form's /search/ target is itself a static page whose script reads location.search and runs the query:

HTML
<search>
  <form action="/search/">
    <label for="q">Search this site</label>
    <input id="q" name="q" type="search">
    <button>Search</button>
  </form>
</search>

This matters when you build the box yourself, as with Lunr or Fuse.

When search returns nothing

The search box loads, but the browser console shows a 404 for /pagefind/…. The index was never generated, or it was generated and not uploaded. Check that the published folder contains pagefind/ — the command runs after the build, so a CI step that uploads before running it, or a dev server serving your source folder, will not have it.

Only a few pages appear in results. One of your templates has data-pagefind-body. Once any page has it, pages without it are not indexed. Add it to every template or remove it.

Pages of a single-page app are missing. Pagefind reads HTML files on disk. If your HTML is an empty <div id="root"> filled by JavaScript at runtime, there is no text to index. Pre-render those routes at build time, feed the content to Pagefind through its Node API, or build a Lunr or Fuse.js index from your source data instead.

Every result matches the navigation. A menu or sidebar outside <nav> gets indexed with the page. Mark it data-pagefind-ignore.

Programmable Search finds old pages but not new ones. It is waiting on Google's crawl. Request indexing for the URL, or submit a sitemap, in Search Console; Google says that request changes both Google Search and your engine, as long as the site is listed under "Sites to search". There is no separate way to push a page into the engine.

If the whole site fits in one navigation menu, a search box is a feature nobody will use, and it adds an index to every build and a script to every page that carries the box. A visitor looking for a word on one long page already has the browser's find-in-page.

Add it when visitors arrive at your site with a question rather than a destination — documentation, a knowledge base, an archive of posts, a catalogue. For a smaller site, a clear menu and a good page title do the job.

Questions

Can I add search to a static site without a backend?

Yes. Build an index from your pages at build time, publish it with them, and search it in the browser. Pagefind does this for any folder of HTML; Lunr and Fuse.js do it with an index you generate yourself.

Does Pagefind work with Hugo, Jekyll, Eleventy or a hand-written site?

Yes. It reads the HTML your generator wrote, not the generator, and its documentation says it works with any static HTML output. Run it on the output folder after each build.

Why does search work after building but not with my dev server?

The pagefind/ folder is created by the indexing step, which runs on the built output. A dev server serving your source files has no index to load. Run npx -y pagefind --site public --serve instead: it indexes the built folder and serves a local preview of it.

Is Pagefind better than Lunr?

For most sites, yes, because the browser downloads only the index chunks a query needs instead of the whole index. Lunr is the simpler fit when you already have the content as JSON and the whole index is small enough to download at once.

Will Google Programmable Search find pages that are not on Google?

No. Its results come from Google's index, so a new page appears only after Google crawls it, and a page marked noindex is kept out of that index, so it never appears.

This site is the product it is written about.

Drag a folder in and read the link back. No account and no card to publish.