How to Use Algolia with Astro: Complete Guide
Step-by-step guide to integrating Algolia with your Astro website.
Algolia is a hosted search API that delivers instant, typo-tolerant search results. If you have ever used a site where search results appear as you type with zero lag, there is a good chance Algolia is behind it. For Astro sites with a lot of content, blog posts, documentation, or product listings, Algolia makes search feel effortless for your visitors.
The setup involves two parts: indexing your content (pushing data to Algolia) and building the search UI (querying Algolia from the frontend). Both are straightforward once you understand the flow.
Prerequisites
- Node.js 18+
- An Astro project (
npm create astro@latest) - An Algolia account (free tier gives you 10,000 search requests per month)
Installation
Install the Algolia client for indexing and the InstantSearch library for the frontend:
npm install algoliasearch instantsearch.js
If you want to use the React version of InstantSearch (useful for interactive Astro islands):
npm install algoliasearch react-instantsearch-hooks-web
Configuration
Get your API keys from the Algolia dashboard under Settings > API Keys. You need:
- Application ID (public, used on frontend)
- Search-Only API Key (public, used on frontend)
- Admin API Key (private, used only for indexing)
Add them to your .env:
PUBLIC_ALGOLIA_APP_ID=your_app_id
PUBLIC_ALGOLIA_SEARCH_KEY=your_search_only_key
ALGOLIA_ADMIN_KEY=your_admin_api_key
ALGOLIA_INDEX_NAME=blog_posts
Create a script to index your content. This runs at build time or as a separate step:
// scripts/index-to-algolia.ts
import algoliasearch from "algoliasearch";
import fs from "fs";
import path from "path";
import matter from "gray-matter";
const client = algoliasearch(
process.env.PUBLIC_ALGOLIA_APP_ID!,
process.env.ALGOLIA_ADMIN_KEY!
);
const index = client.initIndex(process.env.ALGOLIA_INDEX_NAME!);
const postsDir = path.join(process.cwd(), "src/content/posts");
const files = fs.readdirSync(postsDir).filter((f) => f.endsWith(".mdx"));
const records = files.map((file) => {
const raw = fs.readFileSync(path.join(postsDir, file), "utf-8");
const { data, content } = matter(raw);
return {
objectID: data.slug || file.replace(".mdx", ""),
title: data.title,
description: data.description,
content: content.slice(0, 5000), // Algolia has a 10KB record limit
tags: data.tags,
publishDate: data.publishDate,
url: `/blog/${data.slug || file.replace(".mdx", "")}`,
};
});
await index.saveObjects(records);
console.log(`Indexed ${records.length} posts to Algolia`);
Run it with npx tsx scripts/index-to-algolia.ts.
Basic Usage
Build a search component using InstantSearch.js. Since Algolia's search UI needs client-side JavaScript, use an Astro island with a framework component or plain JS:
---
// src/components/Search.astro
---
<div id="searchbox"></div>
<div id="hits"></div>
<script>
import algoliasearch from "algoliasearch/lite";
import instantsearch from "instantsearch.js";
import { searchBox, hits } from "instantsearch.js/es/widgets";
const searchClient = algoliasearch(
import.meta.env.PUBLIC_ALGOLIA_APP_ID,
import.meta.env.PUBLIC_ALGOLIA_SEARCH_KEY
);
const search = instantsearch({
indexName: "blog_posts",
searchClient,
});
search.addWidgets([
searchBox({
container: "#searchbox",
placeholder: "Search articles...",
}),
hits({
container: "#hits",
templates: {
item: (hit) => `
<a href="${hit.url}">
<h3>${hit._highlightResult.title.value}</h3>
<p>${hit._highlightResult.description.value}</p>
</a>
`,
},
}),
]);
search.start();
</script>
Use this component anywhere in your Astro pages:
---
import Search from "../components/Search.astro";
import BaseLayout from "../layouts/BaseLayout.astro";
---
<BaseLayout title="Search">
<h1>Search</h1>
<Search />
</BaseLayout>
Production Tips
Keep your index in sync. Add the indexing script to your build process or trigger it via a webhook whenever content changes. Stale search results frustrate users more than no search at all.
Trim your records. Algolia charges based on records and operations. Only index the fields users actually search against. You do not need the full HTML body in most cases.
Use faceting for filters. Algolia supports faceted search out of the box. Configure facets on fields like tags or category in your Algolia dashboard to let users filter results without extra API calls.
Configure ranking and relevance. In the Algolia dashboard, set your searchable attributes in priority order (title first, then description, then content). This ensures titles match higher than body text matches.
Implement search analytics. Algolia provides analytics on what users search for. Use this data to identify content gaps, popular topics, and queries with zero results.
Alternatives to Consider
- Pagefind if you want a free, build-time search that requires no external service. It generates a static search index during your Astro build.
- Meilisearch if you prefer an open-source search engine you can self-host with similar instant search capabilities.
- Orama if you want a search engine that runs entirely in the browser with no backend required.
Wrapping Up
Algolia and Astro make a strong pair for content-heavy sites that need fast, relevant search. The indexing pipeline is simple, the search UI libraries are mature, and the free tier covers small to medium sites. If your visitors are searching for content and the built-in browser search is not cutting it, Algolia is the industry standard for a reason.
Related Articles
How to Integrate Auth0 with Astro: Complete Guide
Step-by-step guide to integrating Auth0 with your Astro website. Setup, configuration, and best practices.
How to Use AWS Amplify with Astro: Complete Guide
Step-by-step guide to integrating AWS Amplify with your Astro website.
How to Use ButterCMS with Astro: Complete Guide
Step-by-step guide to integrating ButterCMS with your Astro website.