Search your site

Add search to a static Bevel site with a JSON search index you write, or with Pagefind run after the export.

On this page
Program.cscsharp
app.MapStatic("/search-index.json", (ISiteData data, ISiteLinks links) =>
    BevelResults.Json(data.Posts.Select(p => new { p.Title, p.Summary, Url = links.To(p) })));

You have two ways to search a static site. Write a JSON file of your content and filter it in the browser, or index the exported HTML with Pagefind. Pick the JSON file for a small site you control. Pick Pagefind for full-text search over every page.

Option 1: a JSON search index

A route that returns BevelResults.Json(...) exports as a file. The sample blog does this.

samples/Bevel.SampleBlog/Program.cscsharp
app.MapStatic("/search-index.json", (ISiteData data, ISiteLinks links) =>
    BevelResults.Json(data.Posts.Select(p => new
    {
        p.Slug,
        p.Title,
        p.Summary,
        p.Excerpt,
        p.Date,
        p.Tags,
        p.Category,
        Author = p.Author.Name,
        Url = links.To(p)
    })));

The route becomes /search-index.json in the export. links.To(p) gives each post its real URL, with your path base applied.

  1. Choose what to index

    Include what a reader types. Titles, summaries, tags and the first paragraph work well. Leave out the whole body unless your site is small. The sample adds Excerpt, which a processor fills.

  2. Load it in the browser

    Fetch the file once, then filter in memory. Use Links.Asset so the URL has your path base.

    wwwroot/js/search.jsjavascript
    const response = await fetch(indexUrl);
    const posts = await response.json();
    const find = q => posts.filter(p =>
      [p.title, p.summary, p.excerpt, ...p.tags].join(" ").toLowerCase().includes(q.toLowerCase()));

    Here indexUrl is the value of Links.Asset("/search-index.json"), which you pass to the script in a data- attribute.

  3. Keep it out of the sitemap

    If you generate a sitemap with MapSitemap(), it skips non-HTML routes such as .json for you.

Option 2: Pagefind

Pagefind reads your exported HTML and writes a search index next to it, in <site>/pagefind/. Your page loads the index on demand. The output is static files, so it works on any host.

Since 0.3

Bevel runs your steps after the export has written its files. Register one that starts the Pagefind binary.

Program.cscsharp
using System.Diagnostics;

builder.AddBevel(options =>
{
    options.AfterExport.Add(async (context, cancellationToken) =>
    {
        var start = new ProcessStartInfo("pagefind") { RedirectStandardOutput = true };
        start.ArgumentList.Add("--site");
        start.ArgumentList.Add(context.OutputDirectory);

        using var process = Process.Start(start)
            ?? throw new InvalidOperationException("Could not start pagefind.");
        await process.WaitForExitAsync(cancellationToken);
        if (process.ExitCode != 0)
            throw new InvalidOperationException($"pagefind exited with {process.ExitCode}.");
    });
});

A step that throws fails the export, and --bevel-build exits with code 1. context.OutputDirectory is the folder that was just written. You can also register a class with builder.Services.AddBevelExportStep<TStep>().

Mark what to index

Pagefind indexes an element that has data-pagefind-body. Anything outside it is ignored. Add data-pagefind-ignore to a part inside, such as a breadcrumb, to skip it. This site puts data-pagefind-body on the article element and filters by section with data-pagefind-filter. See DocArticle.razor.

Serve the index under a path base

Pagefind writes to pagefind/ at the root of the export. Your site is hosted under PathBase, so the browser must load <PathBase>/pagefind/pagefind.js. This site's search script finds its base from the page and loads the index from there. See search.js.