chan.dev / posts

Search Astro Site with Pagefind

🌱 This post is in the growth phase. It may still be useful as it grows up.

Install Pagefind

Terminal window
pnpm install pagefind

Run on local build

Terminal window
pnpm build && pnpm exec pagefind --site dist

Add postbuild script to build search records

{
"scripts": {
"postbuild": "pagefind --site dist"
}
}

Add /search route

Note: I can’t currently run this locally because I’m using hybrid rendering. preview is not supported, meaning I can’t locally serve a postbuild preview.

<html>
<link href="/pagefind/pagefind-ui.css" rel="stylesheet" />
<script src="/pagefind/pagefind-ui.js" is:inline></script>
<main>
<h1>Search</h1>
<div id="search"></div>
</main>
<script is:inline>
window.addEventListener('DOMContentLoaded', (event) => {
new PagefindUI({element: '#search', showSubResults: true})
})
</script>
</html>