How to Add Search to Any Kind of Static Site Using Pagefind
Introduction
If you are an early reader of web Dong, you may have noticed that the original search function in the navigation bar is gone. This is because I recently changed the search functionality from using Fuse.js (a fuzzy search library) to using pagefind for the website’s search functionality.
Fuse.js was actually sufficient for the current search needs of the website, but it was expected that as the site grew, it would encounter bottlenecks. Coincidentally, with the release of Pagefind 1.0, I decided to replace the original search functionality with Pagefind. Of course, there were additional reasons behind this, such as my desire to remove preact used for the original UI.
About Pagefind
Pagefind is a search library written in Rust and implemented through WebAssembly. Its purpose has been clear from the beginning: to provide a ready-to-use search solution for any static webpage.
- Fast search
- Provides ready-made UI
- Supports search in Chinese and Japanese
- Supports searching any static files
- Supports filtering, sorting, custom search data, and index weighting
This made me feel that it is a mature and ready-to-use solution, so I decided to adopt Pagefind to implement the search functionality for this Astro static site.
Step 1: Create an Index
The operation principle of Pagefind is very simple; you just need to create an index for the generated static site. The index is essentially a pagefind
folder filled with the files needed by Pagefind. The process does not require installing any related packages; you just need to run npx -y pagefind --site public --serve
to download Pagefind and create the index in real-time. I placed this process after the site is built.
After building, you will get results similar to the following, along with an additional pagefind
folder:
This uses the Extended
version, which means this version has special support for languages like Chinese and Japanese, so if the blog uses these languages, pay special attention to using this version.
Step 2: Add Search Functionality
Pagefind comes with a ready-made search UI and includes a click-to-load feature. You just need to add the following code to the page where you want to add the search functionality:
You can also choose not to use the ready-made UI and simply use Pagefind’s search functionality to get search results:
Summary
In less than 3 steps, your website will have a custom search functionality powered by WebAssembly! 🙌🏻 You may want to make some custom settings based on your needs, such as this blog has made some additional settings for Pagefind:
- Modify default UI styles to match website style
- Sort search results by time
- Search classification based on existing classification system
Further Reading
- For details on how to add Fuse.js search functionality to a static site, refer to: Astro 系列文第二十日:實作搜尋功能