Pagefind is the pragmatic answer to search on a static site: it does the indexing after your build, splitting the result into small files that the browser only fetches when a search actually happens.

No API keys, no hosted service, no index that goes stale.

1. Install it

npm install -D pagefind

Then run it as part of the build so the index never gets forgotten:

{
  "scripts": {
    "dev": "astro dev",
    "build": "astro build && pagefind --site dist",
    "preview": "astro preview"
  }
}

2. Tell Pagefind what to index

By default it indexes whole pages, which drags in your header, footer and related posts. Scope it to the article body instead by adding one attribute:

<article data-pagefind-body>
  <h1 data-pagefind-meta="title">{post.data.title}</h1>
  <Content />
</article>

Anything outside data-pagefind-body is ignored for that page. Add data-pagefind-ignore to any block inside the body you want excluded — ad slots, newsletter boxes, image captions.

3. Add metadata and filters

Metadata shows up on the result card; filters let visitors narrow results. Put both inside the body:

<span hidden data-pagefind-meta="category" data-pagefind-filter="category">
  {category.name}
</span>
<span hidden data-pagefind-meta="date">{formatDate(post.data.date)}</span>

That gives you result.meta.category, result.meta.date and a category filter with an automatic count per value.

4. Build the search UI

The default Pagefind UI is fine, but a custom one is about 60 lines and looks like the rest of your site. A minimal version:

<form role="search" id="search-form">
  <input id="q" type="search" placeholder="Search posts…" />
</form>
<ol id="results"></ol>
<p id="status" aria-live="polite"></p>
const input = document.getElementById('q');
const list = document.getElementById('results');
const status = document.getElementById('status');

// loaded lazily: no cost until the page needs it
const pagefind = await import('/pagefind/pagefind.js');
await pagefind.options({ excerptLength: 24 });

let timer;
input.addEventListener('input', () => {
  clearTimeout(timer);
  timer = setTimeout(async () => {
    const term = input.value.trim();
    if (term.length < 2) {
      list.innerHTML = '';
      status.textContent = 'Type at least 2 characters.';
      return;
    }

    const search = await pagefind.search(term);
    const results = await Promise.all(
      search.results.slice(0, 10).map((r) => r.data())
    );

    status.textContent = `${search.results.length} results for “${term}”`;
    list.innerHTML = results
      .map(
        (r) => `
        <li>
          <a href="${r.url}">
            <strong>${r.meta.title}</strong>
            <span>${r.meta.category ?? ''}</span>
            <p>${r.excerpt}</p>
          </a>
        </li>`
      )
      .join('');
  }, 180);
});

The excerpt already contains <mark> tags around matches — that is why you can interpolate it as HTML and style it with one CSS rule:

mark {
  background: #e0e7ff;
  color: #312e81;
  border-radius: 2px;
}

5. Add filters to the UI

pagefind.filters() returns every filter value with its count, so the buttons render themselves:

const filters = await pagefind.filters();
const categories = filters.category ?? {};

const buttons = Object.entries(categories).map(([name, count]) => {
  const button = document.createElement('button');
  button.textContent = `${name} (${count})`;
  button.onclick = async () => {
    const search = await pagefind.search(input.value, {
      filters: { category: name },
    });
    // …same rendering as above
  };
  return button;
});

Keep the filter state in the URL (?q=invoice&category=Legal%20Tricks) so a search result can be shared.

6. Verify before you ship

npm run build
npm run preview

Then check four things:

Check What you should see
dist/pagefind/pagefind.js exists The build script ran Pagefind
Searching a phrase from one post That post appears first
Searching a word from your footer Nothing (scope is working)
Category buttons Counts match your post totals

Troubleshooting and common mistakes

Search finds everything, including nav links. data-pagefind-body is missing, or it is on a wrapper that also contains the header and footer.

No results at all after deploy. The host ignored the pagefind/ directory. Check that it is in the published output — for most static hosts, if it exists in dist/, it is live.

The import throws in dev. Expected. Guard it:

try {
  pagefind = await import('/pagefind/pagefind.js');
} catch {
  status.textContent = 'Search works in the production build.';
}

Stale results. Pagefind indexes dist/ at build time. If you edit a post, rebuild before testing.