DEV Community

David Li
David Li

Posted on

Adding search to static sites with pagefind

In this article I will cover how add pagefind to an astro site. This code is accessible in this github repo for those interested.

For pagefind, you can install it with the following command:

npm install pagefind
Enter fullscreen mode Exit fullscreen mode

Then in your package.json file make sure you generate the search after your static site is built

  {
  "scripts": {
    ...
    "build": "astro build",
    "postbuild": "pagefind --source dist",
  },
  }

Enter fullscreen mode Exit fullscreen mode

Then you can run the following command to search for content in your site:

<link href="/_pagefind/pagefind-ui.css" rel="stylesheet" />
<script src="/_pagefind/pagefind-ui.js" type="text/javascript">

</script>
<div id="search" class="ml-3 p-4"></div>
<script>
  window.addEventListener('DOMContentLoaded', (event) => {
    new PagefindUI({ element: '#search' });
  });
</script>
Enter fullscreen mode Exit fullscreen mode

As described by the pagefind documentation, you can use the search bar to search for content in your site.

Another thing to keep in mind is that you can choose to not index certain pages.

<body>
  <main>
    Content goes here
  </main>
<div class="bg-slate-900 text-gray-100" data-pagefind-body >
</div>
</body>
Enter fullscreen mode Exit fullscreen mode

To index page content, use data-pagefind-body attribute on the page.

<body class="bg-slate-900 text-gray-100" data-pagefind-body >
    <main>
    Content goes here
  </main>
</body>
Enter fullscreen mode Exit fullscreen mode

To see this in action, you can look at my personal website repository.

https://github.com/FriendlyUser/astro-tech-blog

References

Top comments (0)