🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Content & MDX••By Komal Nakrani

Astro Search Without a Library: A 60-Line Version

Add Astro search without a library: build a search.json index from your content collection, then filter it in the browser with a small script and an accessible form.

#Astro#Astro Search#Content Collections#JavaScript

For simple Astro search without a library, build a static search.json endpoint from your content collection with titles, descriptions and tags, then fetch it on a search page and filter it in the browser as the visitor types. It works on any static host, adds a few kilobytes of JavaScript, and suits sites with up to a few hundred pages.

Key Takeaways

  • A static endpoint turns your collection into a small JSON index at build time.
  • The index loads only when someone uses search, not on every page.
  • Match every word of the query against title, description and tags, and rank title matches first.
  • Past a few hundred pages or for full-text search, switch to Pagefind.

Build the index

// src/pages/search.json.ts
import type { APIRoute } from 'astro';
import { getCollection } from 'astro:content';

export const GET: APIRoute = async () => {
  const posts = await getCollection('blog', ({ data }) => !data.draft);
  const index = posts.map((post) => ({
    url: `/blog/${post.id}/`,
    title: post.data.title,
    description: post.data.description,
    tags: post.data.tags ?? [],
  }));
  return Response.json(index);
};

On a static build this becomes dist/search.json. Keep the index to fields people search for; adding full post bodies makes the file grow with every article. Our API endpoints guide explains static endpoints, and the Content Collections docs page covers the collection itself.

The search page

---
// src/pages/search.astro
import BaseLayout from '../layouts/BaseLayout.astro';
---
<BaseLayout title="Search">
  <form role="search" action="/search/" id="search-form">
    <label for="q">Search articles</label>
    <input id="q" name="q" type="search" autocomplete="off" />
  </form>
  <p id="search-status" aria-live="polite"></p>
  <ul id="search-results"></ul>
</BaseLayout>

<script>
  type Entry = { url: string; title: string; description: string; tags: string[] };

  const input = document.getElementById('q') as HTMLInputElement;
  const list = document.getElementById('search-results')!;
  const status = document.getElementById('search-status')!;
  let index: Entry[] | null = null;

  const normalize = (s: string) =>
    s.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '');

  async function search(query: string) {
    index ??= await fetch('/search.json').then((r) => r.json());
    const words = normalize(query).split(/\s+/).filter(Boolean);
    if (!words.length) { list.replaceChildren(); status.textContent = ''; return; }

    const results = index!
      .map((entry) => {
        const title = normalize(entry.title);
        const rest = normalize(`${entry.description} ${entry.tags.join(' ')}`);
        if (!words.every((w) => title.includes(w) || rest.includes(w))) return null;
        const score = words.filter((w) => title.includes(w)).length;
        return { entry, score };
      })
      .filter((r) => r !== null)
      .sort((a, b) => b.score - a.score)
      .slice(0, 20);

    list.replaceChildren(...results.map(({ entry }) => {
      const li = document.createElement('li');
      const a = document.createElement('a');
      a.href = entry.url;
      a.textContent = entry.title;
      const p = document.createElement('p');
      p.textContent = entry.description;
      li.append(a, p);
      return li;
    }));
    status.textContent = `${results.length} result${results.length === 1 ? '' : 's'}`;
  }

  let timer: number | undefined;
  input.addEventListener('input', () => {
    clearTimeout(timer);
    timer = window.setTimeout(() => search(input.value), 150);
  });

  const initial = new URLSearchParams(location.search).get('q');
  if (initial) { input.value = initial; search(initial); }
</script>

Details worth keeping:

  • textContent, not innerHTML, for results. Titles come from your content, but it’s a good habit that rules out injection.
  • aria-live="polite" announces the result count to screen reader users without interrupting them.
  • The form still works without JavaScript: submitting reloads /search/?q=..., and the script reads q on load, so search links are shareable.
  • Accent folding with normalize('NFD') makes “cafe” match “café”.
  • Lazy index: search.json is fetched on the first keystroke, so the page loads instantly.

Astro bundles and minifies the script, as described in our script tag guide.

When to switch to a real search tool

This approach matches words in a few fields. It doesn’t do typo tolerance, stemming (a search for “ran” won’t find “run”) or search inside full article text. Once you need those, or the index passes a few hundred kilobytes, use Pagefind, which indexes your built HTML and loads only the chunks a query needs. The Pagefind vs Algolia comparison covers hosted options. For a ready-made front end, blog and editorial themes give you post listings to put this search above.

FAQ

How do I add search to a static Astro site?

Generate a JSON index of your pages at build time with a static endpoint, then filter it in the browser on a search page. For larger sites, use Pagefind, which builds a full-text index from your HTML and also works on static hosts.

Does client-side search hurt SEO in Astro?

No. Search results pages are generated in the browser and shouldn’t be indexed anyway. Your articles stay as static HTML, and the search script only loads on the search page.

How big can a client-side search index get?

Keep it small enough to download quickly on mobile, roughly under 100 to 200 KB compressed. Titles, descriptions and tags for a few hundred posts fit easily; full article text does not.