Duong Hoang Nam

Search Articles

Find AI, technology, and programming guides

Press Esc to closeFull Search Page →
Technology

How to Add Fast Full-Text Search to Astro with Pagefind (2026 Guide)

Add fast full-text search to your Astro website with Pagefind. Learn indexing, UI integration, deployment, performance, and troubleshooting.

By Duong Hoang Nam
How to Add Fast Full-Text Search to Astro with Pagefind (2026 Guide)

A growing website needs more than good navigation.

When your Astro blog has only five articles, visitors can easily browse them. But as your content library expands to dozens or hundreds of pages, finding a specific tutorial becomes more difficult.

Imagine someone visiting your blog to find an article about GitHub authentication, image optimization, or an n8n automation workflow.

Without search, they may need to browse several categories before finding the right content.

A good search experience solves that problem.

For a static website, however, adding search can raise several questions:

  • Do you need a database?
  • Should you build a dedicated search API?
  • Will search increase JavaScript and network usage?
  • How do you keep the index updated when new articles are published?
  • Can you control which parts of your website appear in search results?

One practical solution is Pagefind, an open-source search library designed for static websites.

In this guide, you’ll learn how to integrate Pagefind with Astro, build a searchable index, customize which content is indexed, test search locally, and troubleshoot common deployment issues.

We’ll also look at how to keep the integration maintainable as your website grows.

1. What Is Pagefind?

Pagefind is a static search library that generates a searchable index from your website’s built HTML files.

Instead of requiring a server-side search database, it creates static search assets that can be deployed alongside your website.

The general process looks like this:

Astro Content
     |
     v
Astro Build
     |
     v
Generated HTML
     |
     v
Pagefind Indexing
     |
     v
Static Search Assets
     |
     v
CDN / Hosting
     |
     v
Search in Browser

The key architectural detail is that indexing happens during the build process, not every time a visitor searches.

When someone enters a query, the browser uses Pagefind’s generated assets to retrieve relevant results.

Pagefind also supports chunked search indexes, so the browser does not necessarily need to download an entire large index upfront.

Why Pagefind works well with Astro

Astro is particularly suitable for content-driven websites that generate static HTML.

Pagefind can index that generated HTML without needing to know how Astro components or content collections are implemented.

This separation creates a useful architecture:

  • Astro handles content and page generation.
  • Pagefind handles search indexing.
  • The hosting platform delivers the resulting static files.
  • The browser provides the search interface.

Pagefind works with other static-site generators too, but we’ll focus on Astro.

Official documentation: https://pagefind.app/docs/

Illustrated workflow showing how Astro pages are built, indexed by Pagefind, and searched in the browser

Illustration: Astro generates HTML, Pagefind builds static search assets, and the browser loads search results. Interface and terminal visuals are illustrative.

2. When Should You Use Pagefind?

Pagefind is useful for websites where much of the searchable content is publicly available as static HTML.

Typical examples include personal blogs, documentation websites, tutorial libraries, portfolios with articles, and product knowledge bases.

Consider three common search architectures.

Approach Advantages Limitations
Client-side filtering of a JSON file Simple for very small sites Can become inefficient as content grows
Pagefind static search Build-time indexing, no dedicated search server New content requires rebuilding the index
Dedicated search service Advanced indexing and operational features Additional infrastructure, pricing, or maintenance

Pagefind is not automatically the right choice for every application.

If you’re building a private application with per-user access permissions, frequently changing records, or complex server-side search requirements, a dedicated search backend may be more appropriate.

For a public Astro blog, however, static search is often a sensible starting point.

3. Prepare Your Astro Project

Before installing anything, confirm that you are working in your project’s root directory.

For example:

my-astro-site/
├── public/
├── src/
│   ├── components/
│   ├── content/
│   ├── layouts/
│   └── pages/
├── astro.config.mjs
└── package.json

You should already have an Astro project that can generate a static production build.

For Windows PowerShell, run:

npm.cmd run build

A successful build should generate your website’s output directory.

For a typical static Astro project, this directory is:

dist/

If you have customized Astro’s output directory, use that location in the Pagefind commands instead.

Important: Check your existing configuration first

Before editing package.json, inspect its current scripts.

If your project already runs image processing, sitemap generation, Pagefind, or other post-build tasks, do not replace the existing build command.

Extend your current pipeline only when necessary.

This prevents search integration from accidentally breaking other production features.

4. Install Pagefind

Pagefind can be installed as a project dependency so the build process can invoke a locally available version.

In your Astro project, run:

npm.cmd install -D pagefind

This adds Pagefind as a development dependency.

Next, open package.json.

For a simple Astro project without additional build steps, you can configure:

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

This is an illustrative scripts configuration, not a complete replacement for your existing package.json.

The important part is:

astro build && pagefind --site dist

The && operator ensures that Pagefind runs only if the Astro build succeeds.

The indexer then reads the HTML generated by Astro.

If your project has an image optimization pipeline

Some websites process uploaded CMS images after Astro finishes generating pages.

For example, the existing build pipeline might look like this:

{
  "scripts": {
    "build": "astro build && node scripts/optimize-images.mjs && pagefind --site dist"
  }
}

In this architecture:

  1. Astro generates HTML and other site assets.
  2. The image optimization script creates optimized image variants.
  3. Pagefind indexes the generated website.

This pattern is relevant when your project uses a custom Sharp image-processing workflow.

Do not run Pagefind before the final HTML exists.

The search index needs to represent the pages visitors will actually receive.

5. Create Your First Search Interface

Pagefind provides several interface options, including a prebuilt search UI.

Using the provided interface is an efficient way to get started before building a custom search experience.

For a simple Astro search page, create:

src/pages/search.astro

A minimal example using Pagefind’s web components looks like this:

---
import Layout from "../layouts/Layout.astro";
---


<Layout title="Search">
  <main>
    <h1>Search Articles</h1>


    <p>
      Search tutorials, guides, and technical articles.
    </p>


    <link
      href="/pagefind/pagefind-component-ui.css"
      rel="stylesheet"
    />


    <script
      type="module"
      src="/pagefind/pagefind-component-ui.js"
    ></script>


    <pagefind-modal-trigger>
      Search this website
    </pagefind-modal-trigger>


    <pagefind-modal></pagefind-modal>
  </main>
</Layout>

This example assumes your existing layout accepts a title prop.

Your layout may use a different interface, so adapt the import and props accordingly.

The pagefind-modal-trigger and pagefind-modal elements are provided by Pagefind’s component UI.

The required JavaScript and CSS files will be generated during indexing.

Important: These static asset paths do not exist until Pagefind completes its indexing process.

You may therefore see missing-resource errors if you test the page before running the production build.

For a production website, consider where search should appear.

A standalone /search/ page works well for discoverability, while a header button or modal can make search accessible from every page.

You do not need to implement both initially.

Start with one reliable interface and validate it.

6. Build the Search Index

Now run your production build.

npm.cmd run build

If your build script includes Pagefind, the indexer will run after Astro generates its output.

The result should include a directory similar to:

dist/
├── index.html
├── blog/
├── search/
├── images/
└── pagefind/
    ├── pagefind.js
    └── ...

The exact generated files can differ by Pagefind version and configuration.

The important point is that the pagefind directory exists within the final deployed output.

Verify the search assets

In PowerShell:

Test-Path .\dist\pagefind

Expected result when the directory exists:

True

You can inspect its contents with:

Get-ChildItem .\dist\pagefind

If the directory does not exist, check whether Pagefind actually executed during your build.

Also confirm that --site dist points to the correct output directory.

7. Test Search Locally

A common mistake is to test Pagefind using only the Astro development server.

Pagefind typically works by indexing generated static HTML after the build.

During development, your site may not yet have those generated search assets.

The recommended test is a production-style build followed by a local preview.

Run:

npm.cmd run build

Then:

npm.cmd run preview

Open the local URL shown in your terminal.

Visit:

/search/

Now enter a distinctive term from one of your published articles.

For example, if your website contains an article explaining image optimization, search for a specific concept that appears in that article.

You should verify that:

  1. The expected page appears.
  2. The title is correct.
  3. The result links to the intended URL.
  4. The excerpt is relevant.
  5. Clicking the result opens the correct article.

Repeat with a term from a different article.

This helps confirm that the search index contains more than one page.

Test the negative case

Try a term that does not appear anywhere in your content.

The interface should handle a no-results state gracefully.

A useful search experience must work for both successful and unsuccessful queries.

8. Control What Pagefind Indexes

By default, Pagefind can index the text content of generated HTML pages.

However, not everything on a website belongs in search results.

For example, you may want readers to search article content without indexing repeated navigation labels, unrelated sidebar elements, or decorative interface text.

Pagefind provides HTML attributes that allow you to control indexing.

Use data-pagefind-body

Consider an article layout:

<main>
  <article data-pagefind-body>
    <h1>Building a Fast Astro Website</h1>


    <p>
      This tutorial explains how to optimize
      a content-driven Astro website.
    </p>
  </article>
</main>

The data-pagefind-body attribute marks the content area Pagefind should index.

However, there is an important consequence.

Once Pagefind finds data-pagefind-body on any page, pages without that attribute will not be indexed.

This behavior is useful when you want search results to focus on a selected set of content pages.

It also means you must apply the attribute deliberately.

For example, if you only mark blog article pages, your homepage and category pages may stop appearing in search results.

That may be exactly what you want, but it should be a conscious decision.

Exclude selected elements with data-pagefind-ignore

You can also exclude individual elements.

For example:

<article data-pagefind-body>
  <h1>Understanding Astro Performance</h1>


  <p>
    This paragraph should be searchable.
  </p>


  <aside data-pagefind-ignore>
    Subscribe to receive future updates.
  </aside>
</article>

The promotional aside will be excluded from the indexed body content.

This is particularly helpful when pages contain repeated calls to action or related-content sections.

Avoid excluding useful technical information just to make the index smaller.

The goal is better relevance, not simply fewer words.

Official reference: https://pagefind.app/docs/indexing/

Illustration of Pagefind data-pagefind-body indexing article content and data-pagefind-ignore excluding repeated page elements

Illustration: Use data-pagefind-body for searchable article content and data-pagefind-ignore for selected elements that should not appear in results.

9. Improve Search Result Titles and Metadata

Search quality depends partly on the information shown to readers.

A technically correct search result is less useful if it displays a vague title or an irrelevant excerpt.

Pagefind supports metadata extraction from HTML.

For example:

<h1 data-pagefind-meta="title">
  How to Optimize Images in Astro
</h1>

This explicitly identifies the result title.

Pagefind can also derive metadata automatically from the page structure.

For a CMS-managed blog, think carefully about the relationship between:

  • Article title
  • SEO description
  • Featured image
  • Category
  • Published URL

Your search result should represent the same article that the visitor opens.

If your Astro Content Collection already contains these fields, prefer using those values rather than hardcoding new metadata separately.

Why this matters

Consider two hypothetical search results:

Result A: “Tutorial”

Result B: “How to Fix Broken Images in Decap CMS”

The second title communicates what problem the page solves.

Clear titles help users choose relevant results, while descriptive excerpts explain why a page matches the query.

Official reference: https://pagefind.app/docs/metadata/

10. Understand Search Performance

Pagefind’s architecture can reduce the need for infrastructure because the index is generated at build time and delivered as static assets.

However, that does not guarantee a particular Lighthouse score.

Performance still depends on how the search interface is integrated.

For example, loading a large custom interface on every page might have different performance characteristics from loading search assets only when someone opens search.

To evaluate your implementation, inspect:

  • JavaScript transferred on the homepage
  • Additional network requests when search opens
  • Search response time
  • Search behavior on mobile
  • Layout stability when results appear

Load search only when needed

For a custom search interface, one option is to defer loading the Pagefind search API until the visitor interacts with the search feature.

Conceptually:

async function loadSearch() {
  const pagefind = await import(
    "/pagefind/pagefind.js"
  );


  return pagefind;
}

This example illustrates the loading strategy rather than a complete search component.

Pagefind’s JavaScript API can then be used to execute queries and retrieve result data.

When implementing a custom interface, additional work is required for input handling, result rendering, keyboard accessibility, empty states, and error states.

If you do not need that level of customization, the provided Pagefind UI is a simpler starting point.

11. Deploy Pagefind with Cloudflare Pages

For a static Astro website hosted on Cloudflare Pages, ensure that the full production build runs before deployment.

The generated pagefind assets must be included in the published output directory.

For a typical Astro project, the deployment configuration uses:

Build command:
npm run build


Build output directory:
dist

If your existing build script already includes Pagefind, the deployment process should generate the index as part of the normal build.

Verify the production deployment

After deployment completes, open:

https://example.com/pagefind/pagefind.js

A successful response indicates that the requested JavaScript asset is available.

It does not, by itself, prove that the index contains the correct pages.

Next, open your production search interface and test a query from a known published article.

Check whether:

  • Search assets load without 404 errors.
  • Search results link to the production domain.
  • New articles appear after publishing and rebuilding.
  • Draft content is not accidentally exposed.
  • Search remains usable on mobile.

Important: Draft content and indexing

When using a Git-based CMS Editorial Workflow, unpublished content can exist on separate branches.

If production builds use the published main branch, the production Pagefind index should reflect the HTML generated from that branch.

Preview deployments may contain draft articles if they build the corresponding draft branch.

This is another reason to verify both preview and production environments separately.

A search result appearing in a preview deployment does not necessarily mean it has been published.

12. Troubleshooting Common Pagefind Problems

Here are several issues you may encounter.

Problem 1: Search works after build but not in Astro dev

Possible cause: Pagefind assets have not been generated for the current development output.

What to check: Run the production build and test using the preview server.

Do not assume the development server automatically rebuilds Pagefind’s index.

Problem 2: The browser reports /pagefind/pagefind.js as 404

Possible causes:

  • Pagefind indexing did not run.
  • The build output directory is incorrect.
  • The deployed files do not include the Pagefind directory.
  • Your site uses a base path that changes the asset URL.

What to check:

Test-Path .\dist\pagefind\pagefind.js

If the file exists locally, compare the local preview with the deployed site.

If it does not exist, review your build command and indexing logs.

For component UI integrations, inspect the corresponding generated component assets too.

Possible causes:

  • The article was not included in the build.
  • The index has not been regenerated.
  • The page is excluded through Pagefind indexing attributes.
  • The query does not match the indexed content.
  • The content is only present in an unpublished CMS branch.

What to check:

Review the build output and Pagefind indexing log.

If you are using data-pagefind-body, confirm that the missing article actually contains the attribute in its generated HTML.

Problem 4: Search results contain navigation or promotional text

Possible cause: Repeated page content is being included in indexing.

What to check:

Mark the relevant article body with data-pagefind-body, or use data-pagefind-ignore for selected repeated elements.

Rebuild the site and compare the results.

Problem 5: A newly published article does not appear

Possible cause: The deployed search index still reflects an older build.

What to check:

Confirm the article is published in the appropriate branch and that the deployment completed successfully.

Then verify that Pagefind indexed the generated HTML.

Do not attempt to fix an outdated index by repeatedly uploading the article image.

Possible causes:

  • Incorrect base path
  • Site URL configuration mismatch
  • Index generated from unintended output
  • Preview and production deployments using different paths

What to check:

Inspect the result URL, generated HTML path, Astro base configuration, and deployment environment.

Avoid applying a global URL replacement until you understand the underlying path mismatch.

13. Testing Checklist Before Launch

Illustrated six-step checklist for validating Astro Pagefind search before deployment

Illustration: A suggested verification workflow. The depicted build results and search interface are examples, not independently verified test evidence.

Use this checklist before considering your search feature production-ready.

  • Astro production build completes successfully.
  • Pagefind indexing completes without errors.
  • Generated search assets exist in the output directory.
  • Search interface loads on desktop.
  • Search interface loads on mobile.
  • Known article terms return relevant results.
  • No-result queries display a useful message.
  • Result links open the correct pages.
  • Repeated navigation text is not dominating results.
  • Draft-only articles are excluded from production.
  • New published content appears after deployment.
  • Keyboard interaction is usable.
  • Light and Dark Mode remain readable.
  • Search integration has not introduced unexpected layout shifts.

A successful build alone is not enough.

You should also test whether the feature behaves as visitors expect.

14. Frequently Asked Questions

Is Pagefind free to use?

Pagefind is an open-source project and does not require a paid hosted search service for its standard static-search architecture. Your regular hosting and deployment costs still apply.

Does Pagefind require a database?

No dedicated search database is required for the standard static-site workflow. Pagefind generates the search index from built content.

Can Pagefind index Markdown articles?

Yes, provided your static-site generator renders the Markdown into HTML included in the build that Pagefind indexes.

Pagefind does not automatically publish unpublished CMS Markdown files.

Can I use Pagefind with Decap CMS?

Yes. Decap CMS manages content, Astro generates pages, and Pagefind indexes the generated HTML.

Newly published articles generally become searchable after the appropriate build and deployment completes.

Does Pagefind improve SEO rankings?

Pagefind provides on-site search functionality. It does not directly guarantee higher Google rankings.

Its main value is helping visitors discover content within your website.

Whether it improves user engagement should be evaluated using actual usage data rather than assumed.

Should I use Pagefind or Algolia?

That depends on your requirements.

Pagefind is attractive for public static content and simple deployment.

A dedicated search service may be more suitable when you require specialized ranking, frequent index updates, access-controlled results, or operational features beyond your static search requirements.

Will Pagefind slow down my Astro website?

Not necessarily. The effect depends on how you load the search interface and assets.

Measure the implementation rather than assuming search has no performance cost.

15. Final Thoughts

Adding search to an Astro website does not have to mean building a database-backed search system.

For a content-focused static site, Pagefind offers a practical separation of responsibilities:

Astro generates the website. Pagefind indexes its pages. Static hosting delivers the search assets. The browser provides the user experience.

The implementation itself is relatively straightforward.

The more important engineering decisions involve what gets indexed, when the index is generated, how the interface loads, and how you verify production behavior.

Start with a simple search interface.

Then improve relevance, accessibility, and loading behavior based on actual user needs.

A useful search feature should make existing content easier to discover without introducing unnecessary complexity.


Continue Reading

If you’re developing an Astro website, these related tutorials provide additional context:

Official References

  1. Pagefind — Getting Started
  2. Pagefind — Running Pagefind
  3. Pagefind — Configuring Indexed Content
  4. Pagefind — Metadata
  5. Pagefind — Configuration Options
  6. Astro — Scripts and Event Handling

Technical note: The examples in this article demonstrate documented integration patterns. They are not presented as independently benchmarked results. Adapt commands and component interfaces to your project’s existing configuration and verify them with a production build before deployment.

About the Author

Duong Hoang Nam

Duong Hoang Nam

Software engineer sharing practical tutorials, real-world experiments, and insights on AI tools, automation, and web development.

Read My Story →

Related Articles