Search

Page content:

Every build creates a search index with Pagefind, and so does the dev server. In a build, the index is a set of static files in out/pagefind/, so search needs no server or third-party service, and the browser only downloads the parts of the index a query needs.

Search in the default theme

The default theme has a search box in its header that uses the index. There is nothing to set up.

Add search to your own layouts

Pagefind comes with a ready-made search interface. Load it from the index folder and start it in an onRender callback, so it's set up again after each page change (see Navigation without reloads):

html
<div id="search"></div>
js
import { onRender } from 'postdoc/page';

onRender(() => {
  const container = document.getElementById('search');

  if (!container || container.childElementCount) {
    return;
  }

  // The index is in the output folder, under the site's base path.
  const pagefindPath = import.meta.env.BASE_URL + 'pagefind/';

  if (!document.querySelector('link[href$="pagefind-ui.css"]')) {
    document.head.append(Object.assign(document.createElement('link'), {
      rel: 'stylesheet',
      href: pagefindPath + 'pagefind-ui.css'
    }));
  }

  const showSearch = () => new PagefindUI({ element: '#search', showSubResults: true, bundlePath: pagefindPath });

  if (window.PagefindUI) {
    showSearch();
  } else {
    document.head.append(Object.assign(document.createElement('script'), {
      src: pagefindPath + 'pagefind-ui.js',
      onload: showSearch
    }));
  }
}, {
  forPage: () => true
});

The script and the stylesheet are added from code rather than in the layout, because they only exist after a build. Pagefind's search UI options go in the object passed to PagefindUI.

Choose what gets indexed

Pagefind indexes the whole page, menus included. To index only the main content, add data-pagefind-body to its element in your layouts:

html
<main data-pagefind-body>
  <%- page.content %>
</main>

Once any page has data-pagefind-body, pages without it are left out of the index, so add it to every layout.

To leave out a part of the page, add data-pagefind-ignore to it. Pagefind's indexing guide describes more attributes, such as the ones that set a result's title or add filters.

Search during development

The dev server builds the index in memory when it starts, and again when you change a page, so search works there too.

Settings

postdoc.config.jsjs
export default {
  pagefind: {
    // Set to false to build without a search index.
    enabled: true,

    // Where the index goes, relative to the output folder.
    outputDir: 'pagefind',

    // Pagefind indexing options.
    options: {
      forceLanguage: 'en'
    }
  }
};

The index treats every page as English. For a site in another language, set forceLanguage to its language code, such as 'de'.

Edit this page on GitHub