To add Algolia search to an Astro site, generate a JSON file of your pages at build time from content collections, push those records to an Algolia index with the admin API key in CI, and query the index from the browser with the search-only key and the algoliasearch/lite client. Astro has no official Algolia integration, and it doesn’t need one: the whole Astro Algolia setup is one endpoint, one script and one small client component.
This guide builds that pipeline for an Astro 7 blog or docs site, explains which key goes where, and covers when Algolia is worth it over a static index like Pagefind.
Key Takeaways
- Build the record list with a static endpoint such as
src/pages/search-index.json.tsusinggetCollection().- Push records from CI after
astro buildwith the admin key, which never ships to the browser.- Query from the browser with the search-only key, which is safe to expose as a
PUBLIC_variable.- Split long pages into one record per section so results link to the right heading.
- Docs sites built with Starlight can use Algolia DocSearch through
@astrojs/starlight-docsearchinstead.
How Algolia fits a static Astro site
Algolia is a hosted search API. You send it records (JSON objects), it stores them in an index, and your site queries that index over HTTPS. Because the index lives on Algolia’s servers, search works the same on a fully static Astro build as on a server-rendered one. No adapter is required.
The flow has three parts:
- Extract. At build time, Astro turns your content into records: title, URL, description, headings and body text.
- Push. A Node script reads those records and replaces the contents of an Algolia index.
- Query. A small script in the browser sends the visitor’s query to Algolia and renders the hits.
Keeping extraction inside Astro matters. Your content collections already know every slug, title and draft flag, so the index can never drift from what the site actually publishes.
Step 1: create the index and API keys
In the Algolia dashboard, create an application and an index, for example blog. Under API Keys you’ll find:
| Key | Where it lives | Can it be public? |
|---|---|---|
| Application ID | Browser and CI | Yes |
| Search-only API key | Browser | Yes, it can only read |
| Admin API key | CI secrets only | No, it can write and delete |
Put the public values in .env so Astro exposes them to client code:
# .env
PUBLIC_ALGOLIA_APP_ID=YourAppId
PUBLIC_ALGOLIA_SEARCH_KEY=your-search-only-key
PUBLIC_ALGOLIA_INDEX=blog
The admin key goes into your CI provider’s secret store as ALGOLIA_ADMIN_KEY. Never prefix it with PUBLIC_ and never import it in a component. If you prefer typed variables, declare them with astro:env as covered in the environment variables guide.
Step 2: generate records with a static endpoint
A static endpoint runs once at build time and writes a file into dist/. This one reads the blog collection and emits one record per section, split at ## headings:
// src/pages/search-index.json.ts
import type { APIRoute } from 'astro';
import { getCollection } from 'astro:content';
function sections(body: string) {
// Split raw Markdown at H2 headings; strip code fences and markup.
const clean = body.replace(/```[\s\S]*?```/g, '').replace(/[#*_`>\[\]()]/g, '');
return clean.split(/\n(?=## )/).map((chunk) => {
const [first, ...rest] = chunk.trim().split('\n');
return { heading: first.replace(/^#+\s*/, ''), text: rest.join(' ').slice(0, 2000) };
});
}
function slugify(s: string) {
return s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
}
export const GET: APIRoute = async () => {
const posts = await getCollection('blog', ({ data }) => !data.draft);
const records = posts.flatMap((post) =>
sections(post.body ?? '').map((s, i) => ({
objectID: `${post.id}-${i}`,
title: post.data.title,
description: post.data.description,
heading: i === 0 ? null : s.heading,
url: i === 0 ? `/blog/${post.id}/` : `/blog/${post.id}/#${slugify(s.heading)}`,
text: s.text,
tags: post.data.tags,
})),
);
return new Response(JSON.stringify(records));
};
A few details worth copying:
objectIDis stable. Algolia uses it to update records in place. Building it from the entryidand section index means a rebuild replaces records rather than duplicating them.- Text is truncated. Algolia limits record size, and the limit depends on your plan. Splitting by section and capping each record keeps you well under it and gives better results, because a hit points to the paragraph that matched.
- The anchor matches Astro’s heading IDs for plain-text headings. If your headings contain code or punctuation, use the
headingsarray fromrender(entry)instead of slugifying by hand.
Run npm run build and check that dist/search-index.json exists and looks sensible.
Step 3: push records from CI
Install the client:
npm install algoliasearch
Then add a small script that reads the built file and replaces the index contents. replaceAllObjects writes to a temporary index and swaps it in, so search never shows a half-updated index:
// scripts/algolia-push.mjs
import { readFile } from 'node:fs/promises';
import { algoliasearch } from 'algoliasearch';
const { PUBLIC_ALGOLIA_APP_ID, ALGOLIA_ADMIN_KEY, PUBLIC_ALGOLIA_INDEX } = process.env;
if (!ALGOLIA_ADMIN_KEY) {
console.log('ALGOLIA_ADMIN_KEY not set, skipping index push');
process.exit(0);
}
const records = JSON.parse(await readFile('dist/search-index.json', 'utf8'));
const client = algoliasearch(PUBLIC_ALGOLIA_APP_ID, ALGOLIA_ADMIN_KEY);
await client.replaceAllObjects({ indexName: PUBLIC_ALGOLIA_INDEX, objects: records });
await client.setSettings({
indexName: PUBLIC_ALGOLIA_INDEX,
indexSettings: {
searchableAttributes: ['title', 'heading', 'description', 'text'],
attributesForFaceting: ['searchable(tags)'],
attributesToSnippet: ['text:20'],
distinct: false,
},
});
console.log(`Pushed ${records.length} records`);
Wire it into package.json so it runs after the build:
{
"scripts": {
"build": "astro build",
"search:push": "node scripts/algolia-push.mjs"
}
}
In CI, run npm run build && npm run search:push with the three variables set. Keeping the push as a separate step means local builds and pull request previews don’t overwrite your production index. The GitHub Actions workflows guide shows how to add secrets and a deploy job.
Step 4: add the search box
The lite client only contains search methods, which keeps the browser bundle small. Install nothing extra, it ships inside algoliasearch:
---
// src/components/AlgoliaSearch.astro
---
<div class="search">
<label for="q" class="sr-only">Search articles</label>
<input id="q" type="search" placeholder="Search articles" autocomplete="off" />
<ul id="hits" aria-live="polite"></ul>
</div>
<script>
import { liteClient } from 'algoliasearch/lite';
const client = liteClient(
import.meta.env.PUBLIC_ALGOLIA_APP_ID,
import.meta.env.PUBLIC_ALGOLIA_SEARCH_KEY,
);
const indexName = import.meta.env.PUBLIC_ALGOLIA_INDEX;
const input = document.querySelector<HTMLInputElement>('#q')!;
const list = document.querySelector<HTMLUListElement>('#hits')!;
let timer: number | undefined;
input.addEventListener('input', () => {
clearTimeout(timer);
timer = window.setTimeout(async () => {
const query = input.value.trim();
if (!query) return (list.innerHTML = '');
const { results } = await client.search({
requests: [{ indexName, query, hitsPerPage: 8 }],
});
const hits = 'hits' in results[0] ? results[0].hits : [];
list.replaceChildren(
...hits.map((hit: any) => {
const li = document.createElement('li');
const a = document.createElement('a');
a.href = hit.url;
a.textContent = hit.heading ? `${hit.title}: ${hit.heading}` : hit.title;
li.append(a);
return li;
}),
);
}, 150);
});
</script>
The script is a normal Astro <script>, so Astro bundles it and inlines the PUBLIC_ values at build time. The 150 ms debounce stops every keystroke from becoming a request, which matters because Algolia bills by search request. Building elements with textContent instead of innerHTML keeps record content from injecting markup.
If you want a full search UI with facets, highlighting and pagination, Algolia’s InstantSearch.js works in the same <script> tag, and React InstantSearch works inside a React island with client:idle. The island or script guide helps decide which to use.
Algolia DocSearch for documentation sites
If you run a documentation site, Algolia’s DocSearch program crawls your site for you and provides a search modal. Starlight supports it through the @astrojs/starlight-docsearch plugin, which swaps Starlight’s default Pagefind search for DocSearch with an app ID, API key and index name in the config. You skip the extraction and push steps entirely, but you depend on Algolia’s crawler configuration and on acceptance into the program. Read Starlight’s site search docs for the current setup.
Algolia or Pagefind for Astro
Most Astro sites don’t need a hosted search API. Pagefind indexes your built HTML and serves the index as static files, so there is no account, no key and no per-search cost. Algolia earns its place when you need things a static index can’t give you:
- Typo tolerance and ranking you can tune in a dashboard, with synonyms and query rules.
- Analytics on what visitors search for and which searches return nothing.
- Very large or frequently changing content, where shipping an index to every browser stops making sense.
- Search across several sites or data sources from one index.
Choose Pagefind if your site is a blog, portfolio or docs site under a few thousand pages and you want zero running cost. Choose Algolia if search is a core feature, you need analytics and relevance controls, or your content lives in several systems. The Pagefind vs Algolia comparison goes deeper, and the Pagefind setup guide covers the static route.
Common problems
Search returns nothing in production. Check that the push step ran with the production index name and that the browser uses the same index. The browser network tab shows the request and Algolia’s error message.
Duplicate results after renaming a post. replaceAllObjects removes records that are no longer in the file. If you switched to saveObjects for incremental updates, you also need to delete old IDs yourself.
Draft posts appear in search. Filter them in the endpoint with the same condition your pages use, as in the getCollection filter above.
Admin key in the bundle. Search the built files with grep -r ALGOLIA_ADMIN dist/. If it appears, a component imported it. Rotate the key in the dashboard immediately.
If you’re starting a new content-heavy site, a blog and editorial Astro theme gives you collections, tags and layouts already structured for an index like this.
FAQ
Does Astro have an official Algolia integration?
No. Astro does not ship an Algolia integration, and the community ones mostly wrap the same steps shown here. A static endpoint for records, a push script in CI and the algoliasearch/lite client in a <script> tag cover the full setup with code you control.
Is it safe to put the Algolia API key in my Astro site?
Only the search-only key. It can read the index but not change it, so exposing it as PUBLIC_ALGOLIA_SEARCH_KEY is the intended use. The admin key can write and delete records and must stay in CI secrets.
Do I need server-side rendering to use Algolia with Astro?
No. Records are built at build time, pushed from CI, and queried directly from the browser against Algolia’s API. A fully static Astro site with no adapter works fine.
How do I keep the Algolia index in sync with my content?
Run the push script after every production build. Because each record’s objectID is derived from the entry ID and replaceAllObjects swaps the whole index, added, changed and deleted pages are all reflected after each deploy.
Should I use Algolia or Pagefind for an Astro blog?
For most blogs, Pagefind is enough: it’s free, static and needs no account. Pick Algolia when you need search analytics, tunable relevance, synonyms, or one index across several sites or data sources.