How to Create a Search Feature for an Astro Website

How to Create a Search Feature for an Astro Website

An enterprise guide to building ultra-fast search in Astro using Pagefind, Typesense, and edge endpoints. Optimize performance, scale, and UX.

Search is often the point where static site architectures hit a wall. Modern static site generators like Astro excel at delivering zero-JavaScript baselines and near-perfect Core Web Vitals. However, querying content dynamically requires balancing client-side payload sizes, indexing overhead, infrastructure costs, and latency targets.

For enterprise applications—ranging from vast technical documentation portals to multi-region marketing hubs—building search into Astro requires choosing the right strategy for your dataset size and update frequency.

This guide explores architectural patterns for integrating search into Astro, comparing static WebAssembly (WASM) indexing against server-side search engines, with production-ready code examples for both paradigms.


Architectural Trade-offs: Choosing the Right Search Pattern

Before writing code, you must evaluate your site’s operational constraints. Search solutions for static and hybrid architectures fall into three primary categories:

  1. Static Build-Time WebAssembly (e.g., Pagefind): Indexes generated HTML static output post-build. Searches run locally on the client using partitioned index files and WASM.
  2. In-Memory Client-Side Engines (e.g., FlexSearch, MiniSearch): Compiles search documents into a JSON index during build time, which is downloaded and executed entirely in client JavaScript.
  3. Hosted / Server-Side Search Engines (e.g., Typesense, Meilisearch, Algolia): Offloads search execution to an external API via Astro API endpoints or direct client SDK calls.

Decision Matrix

Dimension Static WASM (Pagefind) In-Memory JS (MiniSearch) External Engine (Typesense/Algolia)
Document Limit ~100,000+ pages ~5,000 pages Millions+ pages
Initial JS Overhead 0 KB (Lazy-loaded WASM ~30KB) High (proportional to index size) Small SDK (~10–15 KB)
Search Latency Sub-10ms (Local WASM) Sub-5ms (Local RAM) 20–150ms (Network roundtrip)
Infrastructure Cost $0 (Static hosting) $0 (Static hosting) $20–$500+/month (Server/SaaS)
Real-Time Indexing Requires site rebuild Requires site rebuild Instant (API updates)
Access Control (ACL) Not supported Not supported Supported (Scoped JWTs)
                       ┌─────────────────────────────────────────┐
                       │          Astro Build Pipeline           │
                       └────────────────────┬────────────────────┘
                                            │
                                   Generates Static HTML
                                            │
                    ┌───────────────────────┴───────────────────────┐
                    ▼                                               ▼
     ┌─────────────────────────────┐                 ┌─────────────────────────────┐
     │ Static / SSG Pattern        │                 │ Enterprise Dynamic Pattern  │
     │ (Pagefind Post-Processing)  │                 │ (Typesense / Cloud Engine)  │
     └──────────────┬──────────────┘                 └──────────────┬──────────────┘
                    │                                               │
           Static Index Chunks                             Direct API / SSR Endpoint
                    │                                               │
                    ▼                                               ▼
       ┌────────────────────────┐                      ┌────────────────────────┐
       │ Client Browser         │                      │ Astro Edge / SSR Middleware│
       │ (WASM Query Execution) │                      │ (Request Scoping & ACL)│
       └────────────────────────┘                      └───────────┬────────────┘
                                                                   │
                                                                   ▼
                                                       ┌────────────────────────┐
                                                       │ Managed Search Engine  │
                                                       └────────────────────────┘

Pattern 1: Zero-Infrastructure Static Search with Pagefind & WASM

For static sites built with Astro’s default static output mode, Pagefind is the standard approach. Pagefind runs after Astro generates the static site build. It parses raw HTML pages, builds a highly compressed search index, and splits that index into small static chunks.

When a user types a query, Pagefind calculates the hash of the target index fragment, fetches only the required static .pf-index chunks over HTTP, and runs the ranking algorithm locally using WebAssembly.

Step 1: Content Tagging in Astro Markup

Pagefind operates directly on HTML outputs. You can control what gets indexed using data-pagefind-body and refine ranking or filtering via custom attributes.

Update your main layout or content page components (src/layouts/BlogPost.astro):

---
interface Props {
  title: string;
  description: string;
  publishDate: Date;
  category: string;
}

const { title, description, publishDate, category } = Astro.props;
---

<html lang="en">
  <head>
    <title>{title}</title>
  </head>
  <body>
    <header>
      <!-- Navigation elements excluded from indexing -->
    </header>

    <!-- Mark main content area for Pagefind indexing -->
    <main data-pagefind-body>
      <!-- Custom Metadata for Filtering -->
      <span data-pagefind-filter="category">{category}</span>
      <time data-pagefind-meta="date" datetime={publishDate.toISOString()}>
        {publishDate.toLocaleDateString()}
      </time>

      <h1 data-pagefind-weight="10">{title}</h1>
      <p data-pagefind-meta="description">{description}</p>

      <div class="content">
        <slot />
      </div>
    </main>

    <!-- Exclude non-essential elements from indexing -->
    <footer data-pagefind-ignore>
      <p>&copy; {new Date().getFullYear()} Enterprise Corp.</p>
    </footer>
  </body>
</html>

Step 2: Build Pipeline Integration

Pagefind must execute after Astro completes its build step. Configure your build scripts in package.json:

{
  "name": "astro-enterprise-docs",
  "version": "1.0.0",
  "scripts": {
    "dev": "astro dev",
    "build": "astro check && astro build && pagefind --site dist",
    "preview": "pagefind --site dist && astro preview"
  },
  "devDependencies": {
    "astro": "^4.0.0",
    "pagefind": "^1.1.0"
  }
}

Step 3: Accessible Custom Search Interface (Zero-Dependency)

While Pagefind ships with a pre-built UI widget, enterprise applications usually require custom design systems, keyboard shortcuts, and strict accessibility controls.

Here is a native Web Component integration (src/components/SearchModal.astro):

---
// src/components/SearchModal.astro
---

<search-dialog>
  <button id="search-open" aria-expanded="false" aria-controls="search-modal">
    Search documentation... <kbd>⌘K</kbd>
  </button>

  <dialog id="search-modal" aria-label="Site Search">
    <div class="search-container">
      <input
        type="search"
        id="search-input"
        placeholder="Search articles, guides, API refs..."
        autocomplete="off"
        spellcheck="false"
      />
      <div id="search-results" aria-live="polite"></div>
    </div>
  </dialog>
</search-dialog>

<script>
  class SearchDialog extends HTMLElement {
    private pagefind: any = null;
    private dialog: HTMLDialogElement;
    private input: HTMLInputElement;
    private resultsContainer: HTMLElement;
    private openBtn: HTMLButtonElement;

    constructor() {
      super();
      this.dialog = this.querySelector('dialog')!;
      this.input = this.querySelector('input')!;
      this.resultsContainer = this.querySelector('#search-results')!;
      this.openBtn = this.querySelector('#search-open')!;
    }

    connectedCallback() {
      this.openBtn.addEventListener('click', () => this.openSearch());
      this.dialog.addEventListener('click', (e) => {
        if (e.target === this.dialog) this.closeSearch();
      });

      // Global keyboard shortcut (Cmd+K / Ctrl+K)
      window.addEventListener('keydown', (e) => {
        if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
          e.preventDefault();
          this.dialog.open ? this.closeSearch() : this.openSearch();
        }
      });

      this.input.addEventListener('input', (e) => this.handleQuery((e.target as HTMLInputElement).value));
    }

    private async lazyLoadPagefind() {
      if (!this.pagefind) {
        // Dynamic import of post-build generated Pagefind bundle
        try {
          this.pagefind = await import(/* @vite-ignore */ '/pagefind/pagefind.js');
          await this.pagefind.init();
        } catch (e) {
          console.error('Failed to load Pagefind index instance:', e);
        }
      }
    }

    private async openSearch() {
      this.dialog.showModal();
      this.openBtn.setAttribute('aria-expanded', 'true');
      await this.lazyLoadPagefind();
      this.input.focus();
    }

    private closeSearch() {
      this.dialog.close();
      this.openBtn.setAttribute('aria-expanded', 'false');
      this.input.value = '';
      this.resultsContainer.innerHTML = '';
    }

    private async handleQuery(query: string) {
      if (!query.trim() || !this.pagefind) {
        this.resultsContainer.innerHTML = '';
        return;
      }

      const search = await this.pagefind.search(query);
      const results = await Promise.all(search.results.slice(0, 5).map((r: any) => r.data()));

      if (results.length === 0) {
        this.resultsContainer.innerHTML = `<p class="no-results">No results found for "${query}"</p>`;
        return;
      }

      this.resultsContainer.innerHTML = results.map(item => `
        <article class="result-card">
          <a href="${item.url}">
            <h3>${item.meta.title || item.url}</h3>
            <p>${item.excerpt}</p>
          </a>
        </article>
      `).join('');
    }
  }

  customElements.define('search-dialog', SearchDialog);
</script>

<style>
  dialog::backdrop {
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
  }
  /* System UI styling omitted for brevity */
</style>

Pattern 2: High-Scale & Dynamic Search with Typesense and Astro SSR

Static search tools like Pagefind work well up to roughly 100,000 pages. Beyond that, index size, build times, dynamic authorization (e.g., paywalled docs or enterprise RBAC), and sub-second update requirements demand a server-side search engine.

Typesense is an open-source, fast, typo-tolerant search engine ideal for this pattern. Instead of exposing write keys or complex client-side SDKs to the browser, we proxy search requests through secure Astro API Endpoints (SSR/Edge).

[ Client Input ] ──(AbortSignal)──> [ Astro API Endpoint (/api/search) ]
                                                │
                                      (Scopes API Key + Rate Limit)
                                                │
                                                ▼
                                    [ Managed Typesense Cluster ]

Step 1: Secure Astro Server Endpoint

Create a backend API route in Astro to handle search queries, validate requests, hide upstream infrastructure credentials, and apply CDN caching headers.

File: src/pages/api/search.ts

import type { APIRoute } from 'astro';
import Client from 'typesense/lib/Typesense/Client';

// Initialize server-side Typesense client (never exposed to client bundle)
const typesenseClient = new Client({
  nodes: [{
    host: import.meta.env.TYPESENSE_HOST || 'localhost',
    port: parseInt(import.meta.env.TYPESENSE_PORT || '8108'),
    protocol: import.meta.env.TYPESENSE_PROTOCOL || 'http',
  }],
  apiKey: import.meta.env.TYPESENSE_SERVER_API_KEY,
  connectionTimeoutSeconds: 2,
});

export const GET: APIRoute = async ({ request }) => {
  const url = new URL(request.url);
  const query = url.searchParams.get('q');
  const category = url.searchParams.get('category');

  if (!query || query.length < 2) {
    return new Response(JSON.stringify({ results: [] }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  }

  try {
    const searchParameters = {
      q: query,
      query_by: 'title,description,content',
      filter_by: category ? `category:=${category}` : undefined,
      sort_by: '_text_match:desc',
      per_page: 8,
      highlight_full_fields: 'title,description',
      snippet_threshold: 30,
    };

    const searchResults = await typesenseClient
      .collections('documentation')
      .documents()
      .search(searchParameters);

    // Map internal schema to lightweight client contracts
    const payload = searchResults.hits?.map((hit) => ({
      id: hit.document.id,
      title: hit.highlight?.title?.snippet || hit.document.title,
      description: hit.highlight?.description?.snippet || hit.document.description,
      url: hit.document.url,
      category: hit.document.category,
    })) || [];

    return new Response(JSON.stringify({ results: payload }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
        // Cache search queries at CDN edge for 60 seconds
        'Cache-Control': 'public, max-age=60, s-maxage=300, stale-while-revalidate=600',
      },
    });
  } catch (error) {
    console.error('Typesense API Query Error:', error);
    return new Response(JSON.stringify({ error: 'Internal Search Engine Failure' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};

Step 2: Client Framework Island with Cancellation & Debouncing

When querying server endpoints, rapid user typing can trigger race conditions and unnecessary network requests.

Here is a resilient React/Preact island that handles request cancellation via AbortController, debouncing, and robust loading states (src/components/SearchIsland.tsx):

import React, { useState, useEffect, useRef } from 'react';

interface SearchResult {
  id: string;
  title: string;
  description: string;
  url: string;
  category: string;
}

export default function SearchIsland() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<SearchResult[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const abortControllerRef = useRef<AbortController | null>(null);

  useEffect(() => {
    if (query.trim().length < 2) {
      setResults([]);
      setIsLoading(false);
      return;
    }

    setIsLoading(true);

    // Cancel any outstanding fetch request to prevent race conditions
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }

    const controller = new AbortController();
    abortControllerRef.current = controller;

    const handler = setTimeout(async () => {
      try {
        const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
          signal: controller.signal,
        });

        if (!res.ok) throw new Error('Search API returned abnormal status');

        const data = await res.json();
        setResults(data.results);
      } catch (err: any) {
        if (err.name !== 'AbortError') {
          console.error('Failed to fetch search results:', err);
          setResults([]);
        }
      } finally {
        if (!controller.signal.aborted) {
          setIsLoading(false);
        }
      }
    }, 150); // 150ms debounce threshold

    return () => {
      clearTimeout(handler);
    };
  }, [query]);

  return (
    <div className="search-island">
      <div className="input-wrapper">
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Search corporate KB..."
          aria-label="Search site content"
        />
        {isLoading && <span className="spinner" aria-hidden="true" />}
      </div>

      <div className="results-popover">
        {results.map((item) => (
          <a key={item.id} href={item.url} className="result-item">
            <span className="badge">{item.category}</span>
            <h4 dangerouslySetInnerHTML={{ __html: item.title }} />
            <p dangerouslySetInnerHTML={{ __html: item.description }} />
          </a>
        ))}
      </div>
    </div>
  );
}

Mount this component inside an Astro page using an optimal hydration directive:

---
import SearchIsland from '../components/SearchIsland';
---

<!-- Hydrate only when user interacts with or scrolls to the search bar -->
<SearchIsland client:visible />

Production Hardening & Performance Optimization

Deploying search to high-traffic production environments requires addressing security policies, asset delivery, and operational telemetry.

1. Content Security Policy (CSP) & WebAssembly

If your application uses Pagefind, WebAssembly execution will be blocked by strict CSP headers unless you explicitly permit WASM evaluation. Add the following directives to your HTTP security headers (e.g., via Cloudflare Workers, Vercel headers, or Netlify _headers):

Content-Security-Policy: default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline';

Security Note: wasm-unsafe-eval allows WebAssembly modules to compile and run without opening up general JavaScript string-to-code evaluation (unsafe-eval).

2. Edge Caching and Stale-While-Revalidate

For dynamic API search routes, reduce backend database load by leveraging CDN edge networks. Setting strict cache rules allows edge nodes to serve identical search queries instantly:

// Example headers for Astro SSR Endpoints
Response.headers.set(
  'Cache-Control',
  'public, max-age=30, s-maxage=120, stale-while-revalidate=300'
);

3. Telemetry and Zero-Result Tracking

Understanding what users search for—especially when no results are returned—is vital for content strategy. Fire non-blocking analytics events using navigator.sendBeacon to prevent main-thread layout thrashing:

function trackSearchQuery(query: string, resultCount: number) {
  if (!query || query.length < 3) return;

  const payload = JSON.stringify({
    query: query.toLowerCase().trim(),
    count: resultCount,
    timestamp: new Date().toISOString(),
  });

  if (navigator.sendBeacon) {
    navigator.sendBeacon('/api/telemetry/search', payload);
  } else {
    fetch('/api/telemetry/search', {
      method: 'POST',
      body: payload,
      keepalive: true,
    });
  }
}

Decision Framework for Technical Architects

To choose the best search strategy for your enterprise Astro application:

  1. Use Pagefind Static WASM if:

    • Your site relies on static site generation (SSG) with fewer than 100,000 pages.
    • You require a zero-cost infrastructure model with zero API dependencies.
    • Total offline capability or strict privacy compliance (no user query transmitted to remote servers) is mandatory.
  2. Use Server Endpoint Dynamic Search (Typesense/Meilisearch/Algolia) if:

    • Your content updates in real-time via dynamic headless CMS webhooks without triggering full site rebuilds.
    • Search demands role-based access control (RBAC), personalized paywalls, or localized query variations.
    • Your document index exceeds 100,000 records, or requires hybrid vector/semantic search capability.