Site search with no server: Pagefind on a static site
Skunk Yard is plain HTML files on S3, with no server to run a search. It has one now anyway: try it. The search runs entirely in your browser, from an index built when the site deploys.
Try the demo
The smallest working version is in the open-source repository: skunkyard/skunkyard/search. Three pages, A, B, and C, where every word starts with the page's letter, and a search page. Download the folder and run one command:
npx -y pagefind@1.6.0 --site . --serve
Then open http://localhost:1414/ and search for aardvark,
badger, or cactus. Each finds its own page and nothing else.
Why Pagefind
Pagefind is built for static sites. It reads the finished HTML, writes a search index as static files, and the browser downloads only the parts of the index a search needs. It's open source under the MIT license. Other search libraries for the browser ship the whole index as one file and need code to build it. That works for a handful of pages, but every visitor downloads all of it.
How it's wired in
- Mark what to index. Each page's
<main>hasdata-pagefind-body, so results show the page's own words, not the menu or the footer. - Build the index on deploy. The deploy runs
npx -y pagefind@1.6.0 --site sitebefore it uploads. The index isn't in the repository; each deploy builds it fresh. - Add a search page. /search/ loads Pagefind's input, summary, and results components. No other page loads any search code.
- Loosen the security policy, a little. Pagefind searches with
WebAssembly in a web worker. The site's
Content Security Policy now allows
'wasm-unsafe-eval'inscript-srcandworker-src 'self' blob:, as Pagefind's hosting notes describe. Nothing else changed.
What we found
- It's fast to build. Pagefind indexed this site's 15 pages and about 8,000 words in 0.12 seconds.
- Test it under the real policy. The search was tested on a local server that sends the site's Content Security Policy as a header, in headless Chrome: 14 results for skunk, and no policy errors.
- Built files trip link checkers. The search page links to
/pagefind/files that exist only after a deploy, so the site's link test now skips that one folder.