🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
CMS & Integrations••By Komal Nakrani

Astro Search with Pagefind: Static Site Search Guide

Add Astro search with Pagefind: index the build, add the search UI, control what gets indexed, add filters, use the JS API, and test search locally without a server.

#Astro#Search#Pagefind#Static Site

The simplest way to add Astro search is Pagefind: run pagefind --site dist after astro build, and it writes a static search index plus a ready-made search UI into dist/pagefind/. Add a few lines of HTML to load that UI on a search page, and visitors get fast, full-text search with no server, no API key and no monthly bill.

This guide covers the full Pagefind setup on Astro 7, how to control what gets indexed, filters and metadata, the JavaScript API for custom interfaces, and when to choose something else.

Key Takeaways

  • Pagefind indexes your built HTML, so it works with any content source: Markdown, MDX or a CMS.
  • Chain it in package.json: "build": "astro build && pagefind --site dist".
  • Wrap the main content in data-pagefind-body so navigation and footers stay out of results.
  • The index only exists after a build; test with astro preview, not astro dev.
  • Starlight includes Pagefind already; you only need this setup for custom Astro sites.

How Pagefind search works on a static Astro site

Pagefind is an open-source search library built for static sites. After your site is built, it reads every HTML file, extracts the text, and writes a compressed index split into small chunks. In the browser, a small script loads only the chunks needed for the words someone types, so even large sites stay quick to search on slow connections.

That design suits Astro well. Astro already produces complete HTML for every page, Pagefind reads that HTML, and nothing about your content pipeline needs to change. It doesn’t matter whether a page came from a content collection, a CMS or a hand-written .astro file.

Approach Server needed Cost Setup
Pagefind No Free One build step, one component
Algolia, Typesense Cloud, Meilisearch Cloud Hosted by provider Free tier, then paid Index sync plus API keys
Client-side JSON + Fuse.js No Free Generate JSON, write UI; slows on large sites
On-demand search endpoint Yes (adapter) Hosting Write the search yourself

Step 1: Install Pagefind and run it after the build

Install Pagefind as a dev dependency:

npm install -D pagefind

Add it to the build script so the index is generated on every build, locally and on your host:

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

Run npm run build. Pagefind prints how many pages and words it indexed and writes dist/pagefind/. Because hosts like Cloudflare Pages, Netlify and Vercel run npm run build, the index deploys with the site and no host settings change. If you’ve set a custom outDir, point --site at it instead.

There’s also a community integration, astro-pagefind, that runs the indexing as part of astro build and ships a search component. It requires static output. The plain CLI approach above has one fewer dependency and is easy to reason about, so this guide uses it.

Step 2: Add the search UI to a page

Pagefind generates a prebuilt UI in dist/pagefind/. Load its stylesheet and script, and mount it on an element:

---
// src/pages/search.astro
import BaseLayout from '../layouts/BaseLayout.astro';
---
<BaseLayout title="Search" description="Search every article on Example Studio.">
  <h1>Search</h1>
  <link href="/pagefind/pagefind-ui.css" rel="stylesheet" />
  <div id="search"></div>
  <script is:inline src="/pagefind/pagefind-ui.js"></script>
  <script is:inline>
    window.addEventListener('DOMContentLoaded', () => {
      new PagefindUI({ element: '#search', showSubResults: true, showImages: false });
    });
  </script>
</BaseLayout>

is:inline tells Astro not to bundle these scripts, because /pagefind/pagefind-ui.js doesn’t exist until after the build and Astro can’t resolve it. If your site uses base, prefix both paths with it.

showSubResults lists matching headings within a page, which helps on long guides. Style the UI by overriding its CSS variables, for example --pagefind-ui-primary and --pagefind-ui-font, in your global stylesheet so search matches your design.

Pagefind 1.5 introduced a newer Component UI alongside this default UI. Check the Pagefind docs for the current recommendation before you invest in custom styling.

Step 3: Control what Pagefind indexes

By default Pagefind indexes everything inside <body> on every page, which includes your header, navigation and footer. Every result would then match words like “Home” and “Contact”. Mark the real content instead:

---
// src/layouts/PostLayout.astro
const { title, description, category } = Astro.props;
---
<html lang="en">
  <body>
    <header><!-- nav, not indexed --></header>
    <main data-pagefind-body>
      <h1>{title}</h1>
      <p data-pagefind-meta="description">{description}</p>
      <span data-pagefind-filter="category">{category}</span>
      <aside data-pagefind-ignore>
        <!-- related posts, not indexed -->
      </aside>
      <slot />
    </main>
    <footer><!-- not indexed --></footer>
  </body>
</html>

Once any page uses data-pagefind-body, Pagefind indexes only pages that have it, and only that element’s content. That’s useful: tag and pagination pages without the attribute drop out of results automatically.

Attribute Effect
data-pagefind-body Index only this element (and only pages that have it)
data-pagefind-ignore Skip this element and its children
data-pagefind-meta="key" Store this element’s text as metadata for results
data-pagefind-filter="key" Make this value a filter facet
data-pagefind-weight="2" Rank matches in this element higher
data-pagefind-sort="date" Allow sorting results by this value

Pagefind also respects the page’s lang attribute and builds a separate index per language, so multilingual Astro sites get language-correct results without extra work. If you set up i18n routing, the Astro i18n routing guide covers the lang attribute.

Adding filters to Astro search results

Values marked with data-pagefind-filter show up as filter checkboxes in the default UI. Common choices are category, content type and author. For tags, output one element per value:

---
// src/components/PostMeta.astro
const { tags } = Astro.props;
---
<div hidden>
  {tags.map((tag) => <span data-pagefind-filter="tag">{tag}</span>)}
</div>

Hidden elements are still read by Pagefind, so you can attach metadata without changing the visible design. Generating those values from content collection frontmatter keeps them consistent; the content collections guide explains how to type tags and categories in your schema.

Building a custom search UI with the Pagefind JS API

If the prebuilt UI doesn’t fit your design, use Pagefind’s JavaScript API and render results yourself:

---
// src/components/SiteSearch.astro
---
<label for="q">Search articles</label>
<input id="q" type="search" placeholder="Search..." autocomplete="off" />
<ul id="results" aria-live="polite"></ul>

<script>
  const input = document.querySelector<HTMLInputElement>('#q');
  const list = document.querySelector<HTMLUListElement>('#results');
  let pagefind: any;

  input?.addEventListener('input', async () => {
    pagefind ??= await import(/* @vite-ignore */ '/pagefind/pagefind.js');
    const search = await pagefind.debouncedSearch(input.value);
    if (!search || !list) return;
    const items = await Promise.all(search.results.slice(0, 8).map((r: any) => r.data()));
    list.innerHTML = items
      .map((item) => `<li><a href="${item.url}">${item.meta.title}</a><p>${item.excerpt}</p></li>`)
      .join('');
  });
</script>

pagefind.js is loaded only when someone types, so the search costs nothing on page load. debouncedSearch waits for typing to pause and returns null for superseded queries. Each result’s data() call fetches the page’s URL, title, excerpt (with <mark> around matches) and metadata. The @vite-ignore comment stops Vite from trying to resolve the file during the build.

Testing Astro search locally

The index is created after the build, so astro dev has no /pagefind/ folder and the search page shows nothing. To test:

npm run build
npm run preview

astro preview serves dist/, including the index. If you want search in the dev server too, write the index into public/ once with npx pagefind --site dist --output-path public/pagefind, and add public/pagefind/ to .gitignore so a stale index never gets committed.

When Pagefind isn’t the right choice

Pagefind fits almost every content site: blogs, documentation, portfolios and marketing sites. Consider a hosted search service instead when:

  • The content changes constantly and must be searchable within seconds, not after the next build.
  • You need search across data that isn’t in your HTML, like a product database.
  • You need search analytics, synonyms managed by non-developers, or personalized ranking.

For documentation, Starlight uses Pagefind by default, so you get search with no setup; the Astro or Starlight for docs comparison covers that choice.

Komal themes build to static HTML, so Pagefind works on any of them with the build script change above. Themes in the Blog & Editorial category are where search tends to matter most.

FAQ

Is Pagefind free to use with Astro?

Yes. Pagefind is open source and runs entirely at build time and in the visitor’s browser, so there’s no service to pay for. The index is static files served by your existing host.

Why does Pagefind search show nothing in astro dev?

The index is generated after astro build, so the dev server has no /pagefind/ files. Run npm run build then npm run preview, or generate the index into public/pagefind/ for local testing.

Add data-pagefind-body to the main content of pages you want indexed; pages without it are skipped. To skip part of a page, add data-pagefind-ignore to that element.

Does Pagefind work with Astro on-demand rendering?

Pagefind indexes HTML files in the build output, so it only sees prerendered pages. Pages rendered on demand aren’t in dist/ as HTML and won’t be indexed unless you prerender them.

How big is the Pagefind index?

It depends on how much text the site has, but the browser only downloads the chunks a query needs, not the whole index. Pagefind reports the page and word counts after each run, which helps you track growth.