I wanted to implement a search function for a technical blog created with the static site generator Hugo, so I looked into it.
I found pagefind to be a good search library for static sites (SSG). Since it is a completely static full-text search library, it does not require server hosting and can search html files as long as they are available.
Also, the search UI is provided, so it is easy to install.

npx command to install pagefind library Link to heading

Execute the following command.

npx pagefind --source "public"

Add code to front end Link to heading

<link href="/pagefind/pagefind-ui.css" rel="stylesheet">
<script src="/pagefind/pagefind-ui.js"></script>
<div id="search"></div>
<script>
    window.addEventListener('DOMContentLoaded', (event) => {
        new PagefindUI({ element: "#search", showSubResults: true });
    });
</script>

Confirmation of operation on local server Link to heading

  • html file generation with hugo command
hugo
  • http server startup
python3 -m http.server -d public

Usually, hugo uses hugo server -D command to start a local server, but this command does not see the code under public, so the pagefind library does not work. So I used python command to start the server and see the code under the public directory.
If the code is not displayed properly after starting the local server, it may be normalized by modifying the base URL set in the theme’s config.toml.

# example
baseurl = "http://localhost:8000/"
  • Test

Confirm that the pagefind search form exists and perform a full-text search.

Github Actions Link to heading

Since we used Github Actions as work flow, execute npx pagefind –source “public” after generating the site with the hugo command.

,
,
,
- name: 'Build HUGO'
run: hugo --minify

- name: Index pagefind
run: npx pagefind --source "public"
,
,
,