How Pagefind Search Works on My Astro Blog
How Quiet Iterations builds its Pagefind index from Astro’s generated HTML, ships it with the site, and checks that search works after deployment.
When I wrote about deploying Quiet Iterations, I mentioned that the search index goes out with the site. At the time there was one article to find, which gave me an easy way to check that the search box was working. The Cloudflare deployment
Astro builds the pages first
Astro turns the Markdown into HTML and writes it to dist/. Pagefind reads that HTML and writes its search files to dist/pagefind/. The build script runs both steps in that order.
pnpm exec astro buildpnpm exec pagefind --site distOn this blog, pnpm run build:preview runs the whole build, including the checks around those steps. Then pnpm run preview serves the generated files locally. The search box shows sample results under pnpm dev, so I use the built site to check the real index.
What goes into the index
The article template marks the part of the page I want to search. This is the relevant bit of the template, shortened here.
<article data-pagefind-body> <h1 data-pagefind-meta="title">{entry.data.title}</h1> <Markdown class="markdown-content"><Content /></Markdown></article>Pagefind gets the article title and text from the rendered page. The site navigation sits outside the marked area. Draft posts are filtered out before Astro generates the article pages, so there is no draft HTML for Pagefind to pick up. Pagefind’s indexing rules explain how the markup controls what goes in.
I kept the search box from Fuwari. The page loads /pagefind/pagefind.js and the Svelte component uses it to turn a query into links and excerpts. The lookup happens in the browser. Cloudflare serves the same dist/ directory for both the pages and the search files.
A search I can repeat after publishing
I searched for Wrangler on the live site. It appears in the article body, so it is a useful check that search can find a word beyond the title. The result led back to the Cloudflare post.
If a search turns up empty after a deploy, I start by looking for dist/pagefind/pagefind.js in the build output and /pagefind/pagefind.js on the deployed site. If the script loads and every query still comes back empty, I look for failed requests under /pagefind/ in the browser’s Network tab.
If a known search works and one article is missing, I look for that article in the generated HTML and check whether its text is inside data-pagefind-body.
The check I want to keep is simple. After publishing a post, pick a word from the article, search for it on the live site, and open the result. That tells me the post and its search index arrived together.
Keep a little room for curiosity. — Q.