Pagefind: a perfect search for a static website/blog
I fancied a search function for this blog , mainly so that you, dear readers, would be able to click on tags like #DIY and #Tip and see all the posts I have humbly written for you. Bloated blog engines like Hugo or Jekyll achieve this by generating an extra html page for each tag, but this goes strictly against my understanding of minimalism. By the way, minimalism is the reason why this blog uses no engine at all and is generated by a bunch of regexes .
To my shame, previosly, I used Google for tag functionality, clicking on tag lead to a Google search like
www.google.com/search?q=site:developer.run+%22%23DIY%22
. And I was looking for a better search solution just for my blog.
I found Pagefind (pun intended) and was impressed with how easy and fast it was to integrate it into my completely custom scripts. The idea is that after generating your static website html, you feed the output to Pagefind so it indexes all the content (like the big search engines do). The generated index files are served along with the static content, and partially downloaded via JavaScript when the visitor uses the search function. Because of this ingenious approach - no Node.js or PHP on backend is needed, and your own independent search will work on static hostings like Cloudflare pages, Github pages, Netlify etc.
-
I've added a
search page
with
8 lines
of JavaScript and
some css
, and run
npx -y pagefind --site public --serve
(wherepublic
is the output directory). Setup took a minute, indexing itself took less then a second, and I've already had a decent search! -
Then I added
data-pagefind-body
to the
div
surrounding the post content, and the search functionality became perfect as it excluded index pages and auxiliary text like header and footer. - Finally, I've made a tiny change so that the query parameter of the search page is parsed, so that urls like /search?q=test work:
new PagefindUI({ element: "#search", autofocus: true, pageSize: 20 })
.triggerSearch(new URL(window.location.href).searchParams.get('q'));
That was it, the whole process took ~10 minutes and my blog had its very own search.
I wish more people knew about Pagefind. So if you run a blog, please consider it.