Skip to main content
Metaist

Trying pagefind

Adding a search box to the blog.

Previously: Adding a table of contents, Adventures in Eleventy

I've gotten several positive comments about how minimal this website is. But one thing that's missing is a simple search box.

In the past I've used Google Custom Search which is now called "Google Programmable Search Engine". But this time I want to try something more in the spirit of this website: I want something static and local.

It took me so long to write down my thoughts on this that I actually solve this problem for a different website using pagefind which generates a static index after you've built your site.

The actual changes are recorded in issue #7, but all it took was:

$ pnpm add --save-dev pagefind
// eleventy.config.js
const { exec } = require("child_process");

// ...
eleventyConfig.on("eleventy.after", async () => {
  console.log(`[pagefind] building index`);
  exec(`pagefind --site ${eleventyConfig.dir.output}`);
});
// ...
<!-- in _includes/base.njk -->
<div id="search" style="padding-top: 0.5rem;"></div>
<link rel="stylesheet" href="/pagefind/pagefind-ui.css" />
<script src="/pagefind/pagefind-ui.js"></script>
<script>
  window.addEventListener("DOMContentLoaded", (event) => {
    new PagefindUI({ element: "#search", showSubResults: true });
  });
</script>