Add instant search to a static site
A showcase of Pagefind and how to integrate it with a static site.
This article will be a 4 min read.
This blog post was last updated on: 8/21/2023.
I wanted to add a search parameter inside of the blog so that you could find anything fast, either by looking at the
What is Pagefind?
Pagefind is a fully static search library that aims to perform well on large sites, while using as little of your users’ bandwidth as possible, and without hosting any infrastructure.
One benefit of using pagefind is that we can run them inside our hosting environment without relying on a third-party service, like Algolia, Meilisearch or, Typesense.
That being said, it’s super simple to use.
Install Pagefind
Install pagefind as a development dependency. To make simpler our npm scipt to run the actual JS lookup
Create a script to run pagefind
Pagefind needs to run after your site has been built. Add a script to your package.json
to run pagefind after building your site.
Create the “base data”
An issue I ran into so I could style it is “How do I get some of the results to be highlighted?“. The solution is simple: build the site and copy the pagefind data into your public
directory.
public/pagefind
to the .gitignore
There is probably a better way to create this. But this will work the same for development and production.
Add a search bar
Now the fun part of this post. Let’s keep the search bar simple and add it to the Header
component. The component will have a button to open a modal with the search bar. The modal will have a list of results populated by pagefind.
I know it’s a lot of code, but it works wonders. The script has to be inline
to run after the dialog is mounted and the pagefind can be imported after the whole page is loaded.
Excluding elements from the index
Pagefind will find all the text inside the body
element by default, more info . We want to ignore the Header
andFooter
components. We can do this by adding a data-pagefind="ignore"
attribute to the elements we want to ignore and preventing the index form being bloated with duplicated content.
Conclusion
You can now expose a good search experience to your users, without a third-party provider. It took some work to get it working, but it’s worth it. I hope you enjoyed this post and learned something new.
If you want to deploy the site to firebase, I recommend reading this post to modify the build script .
This blog post was last updated on: 8/25/2023.