How to Easily Add Search Functionality to Eleventy Static Sites with Pagefind
Adding search functionality to static sites can be challenging, often requiring complex setups or relying on third-party services. Pagefind offers a simple, lightweight solution that seamlessly integrates with popular static site generators like Eleventy.
What is Pagefind?
Pagefind is a fully static search library designed to perform well on large sites while minimizing bandwidth usage and avoiding the need for hosted infrastructure. Its ease of use and impressive capabilities make it a go-to choice for developers building static sites.
Getting Started with Pagefind for Eleventy
Install Pagefind
Install the Pagefind package using npm:
npm install --save-dev pagefind
Build the Search Index
Add the data-pagefind-body
attribute to the element containing your post content in your Eleventy templates:
<article data-pagefind-body>{{ content | safe }}</article>
Configure Eleventy to run the Pagefind CLI after your site has been built:
const { execSync } = require('child_process')
eleventyConfig.on('eleventy.after', () => {
execSync(`npx pagefind --source dist --glob \"**/*.html\"`, { encoding: 'utf-8' })
})
Add a Search Box
Include the Pagefind stylesheet and optional dark mode styles. Add an element for the search box:
<link href="/_pagefind/pagefind-ui.css" rel="stylesheet">
<div id="search"></div>
<script src="/_pagefind/pagefind-ui.js" onload="new PagefindUI({ element: '#search' });"></script>
Elevate Your Static Site with Pagefind
With minimal effort, you've added powerful search functionality to your Eleventy site, ensuring visitors can easily find the content they're looking for. Pagefind's seamless integration and lightweight nature make it an excellent choice for static sites. Enhance your user experience without sacrificing performance or adding complex dependencies. For more information including filtering, sorting, and more complex indexing options visit Pagefind's docs at https://pagefind.app.
October Featured Tools
Generate a name for your SaaS product.
ExploreMangools SEO tools package. Productive keyword research, SERP analysis, rank tracking and backlink analysis thanks to super easy to use tools. Get 5 lookups per 24 hours, 15 related and 5 competitor keywords per lookup for free. No credit card needed, no strings attached 👍
Explore