Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: A Documentation Site with Sidebar and Search

Build a documentation site in Astro: collection-driven sidebar, table of contents from headings, previous/next links, MDX and static search with Pagefind.

Documentation sites are what Astro was born for: lots of Markdown, long pages, great SEO needs, almost no interactivity. In this project you build the parts every docs site has: an organised sidebar, a per-page table of contents, previous/next navigation and fast search that needs no server.

(If you want to skip building it yourself, the Starlight theme from the Astro team provides all of this. Building it once teaches you what Starlight does for you.)

Content structure

TEXT
src/content/docs/
  getting-started/
    install.md
    first-steps.md
  guides/
    configuration.md
    deployment.mdx
  reference/
    cli.md

Folders become sections. Order is controlled with front matter, not file names, so renaming a file never changes the sidebar.

TypeScript
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { glob } from 'astro/loaders';

const docs = defineCollection({
  loader: glob({ pattern: '**/*.{md,mdx}', base: './src/content/docs' }),
  schema: z.object({
    title: z.string(),
    description: z.string().max(160),
    order: z.number().default(100),
    sidebarLabel: z.string().optional(),
  }),
});
export const collections = { docs };

Step 1: Build the sidebar tree

An entry's id is its path (getting-started/install). Group by the first path segment:

TypeScript
// src/lib/sidebar.ts
import { getCollection } from 'astro:content';

export async function getSidebar() {
  const docs = await getCollection('docs');
  const sections = new Map<string, typeof docs>();
  for (const doc of docs) {
    const [section] = doc.id.split('/');
    (sections.get(section) ?? sections.set(section, []).get(section)!).push(doc);
  }
  return [...sections].map(([section, items]) => ({
    section,
    label: section.replace(/-/g, ' ').replace(/^\w/, (c) => c.toUpperCase()),
    items: items.sort((a, b) => a.data.order - b.data.order),
  }));
}
ASTRO
---
// src/components/Sidebar.astro
import { getSidebar } from '../lib/sidebar';
const sidebar = await getSidebar();
const current = Astro.url.pathname;
---
<nav aria-label="Documentation">
  {sidebar.map((group) => (
    <section>
      <h2>{group.label}</h2>
      <ul>
        {group.items.map((doc) => (
          <li>
            <a href={`/docs/${doc.id}/`} aria-current={current === `/docs/${doc.id}/` ? 'page' : undefined}>
              {doc.data.sidebarLabel ?? doc.data.title}
            </a>
          </li>
        ))}
      </ul>
    </section>
  ))}
</nav>

aria-current="page" marks the active link for assistive technology; style it with [aria-current="page"].

Step 2: The page, table of contents and prev/next

render() returns headings, an array of { depth, slug, text }:

ASTRO
---
// src/pages/docs/[...slug].astro
import { getCollection, render } from 'astro:content';
import { getSidebar } from '../../lib/sidebar';
import Docs from '../../layouts/Docs.astro';

export async function getStaticPaths() {
  const docs = await getCollection('docs');
  return docs.map((doc) => ({ params: { slug: doc.id }, props: { doc } }));
}

const { doc } = Astro.props;
const { Content, headings } = await render(doc);
const toc = headings.filter((h) => h.depth === 2 || h.depth === 3);

const flat = (await getSidebar()).flatMap((g) => g.items);
const index = flat.findIndex((d) => d.id === doc.id);
const prev = flat[index - 1];
const next = flat[index + 1];
---
<Docs title={doc.data.title} description={doc.data.description}>
  <article>
    <h1>{doc.data.title}</h1>
    <Content />
    <nav class="pager">
      {prev && <a rel="prev" href={`/docs/${prev.id}/`}>&larr; {prev.data.title}</a>}
      {next && <a rel="next" href={`/docs/${next.id}/`}>{next.data.title} &rarr;</a>}
    </nav>
  </article>
  <aside aria-label="On this page">
    <ul>{toc.map((h) => <li class={`depth-${h.depth}`}><a href={`#${h.slug}`}>{h.text}</a></li>)}</ul>
  </aside>
</Docs>

Heading IDs come from Markdown processing. Add rehype-autolink-headings if you want clickable anchors.

Step 3: Static search with Pagefind

Pagefind indexes your built HTML and ships a small, chunked index that the browser loads lazily, so no search server is needed.

Terminal
npm install -D pagefind
JSON
{
  "scripts": {
    "build": "astro build && pagefind --site dist"
  }
}

Mark the searchable region (so navigation text is not indexed):

ASTRO
<article data-pagefind-body>
  <Content />
</article>

A tiny search island (no framework):

ASTRO
<div id="search"></div>
<script>
  // Pagefind creates its own UI bundle at /pagefind/ after the build
  import('/pagefind/pagefind-ui.js').then(() => {
    new window.PagefindUI({ element: '#search', showSubResults: true });
  });
</script>

Dev note: the index exists only after a build, so test search with npm run build && npm run preview.

Step 4: Extras that make docs great

  • Code blocks: Shiki highlighting is built in (markdown.shikiConfig sets themes); add a copy button with a small script.
  • Versioning: keep versions in separate collection folders (docs/v1, docs/v2) and add a version switcher.
  • Edit link: build https://github.com/you/repo/edit/main/src/content/docs/${doc.id}.md.
  • Callouts: an MDX component <Note> or a remark plugin for :::note blocks.
  • 404 and redirects for moved pages.
  • i18n: src/content/docs/es/... with the i18n config and getRelativeLocaleUrl.

Try it: build the sidebar tree

The grouping and ordering logic from step 1, using plain arrays.

JS Sidebar from file paths

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: a tiny search index

Pagefind does this at scale with compressed chunks. This stand-in shows the idea: tokenise pages, build an inverted index, rank by term frequency with a title boost.

JS Inverted index search

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does Pagefind get its index?

    Pagefind runs after the build on dist/, producing static index files the browser loads on demand.
  2. 2. What does render() provide for building a table of contents?

    render(entry) returns Content and headings, which you can filter by depth to build an on-page TOC.
  3. 3. Why mark the article with data-pagefind-body?

    Restricting indexing to the article keeps results relevant and the index small.
  4. 4. Which attribute marks the current page link for assistive technology?

    aria-current tells screen readers which navigation item represents the current page.

Summary

  • A docs site is a collection, a sidebar tree, a page template with TOC and prev/next links.
  • Order with front matter, group by folder, mark aria-current.
  • Pagefind provides serverless search from built HTML.
  • Starlight packages all of this if you need a ready-made solution.

Next: Project: A Small Store with Server Rendering