Use Algolia Docsearch with Starlight

Starlight 0.11.0 introduces the ability to override builtin components with your own. With this change, we open up many possibilities for custom navigation, cards, sidebars, or even entirely custom themes! In this first guide, I’ll be replacing the default pagefind searchbar with Algolia Docsearch.

Docsearch is a free algolia search for developer documentation. While Starlight comes with Pagefind pre-configured, Docsearch has the additional features of an Algolia app.

Prerequisites

This guide assumes you have both, an existing Starlight site, and a Docsearch project.

Install dependencies

Docsearch provides a UI component, bundled as JavaScript and CSS packages. You’ll need both of these packages to display the widget.

Terminal window
npm install @docsearch/js @docsearch/css

Create a custom search component

Create a new Search.astro component. Import the CSS in the component script and define a div to contain the UI. In a script tag, import @docsearch/js and initialise it with your project’s details. Finally, add some styles to display the button correctly in the UI.

src/components/Search.astro
---
import '@docsearch/css'
---
<div id="docsearch"></div>
<script>
import docsearch from '@docsearch/js'
docsearch({
container: '#docsearch',
appId: 'YOUR_APP_ID',
indexName: 'YOUR_INDEX_NAME',
apiKey: 'YOUR_API_KEY',
})
</script>
<style>
div {
display: contents;
}
div[data-open-modal] {
width: 100%;
}
@media (min-width: 50rem) {
:global(.DocSearch-Button) {
width: 100%;
max-width: 22rem;
}
}
</style>

Override the existing search component

In astro.config.mjs, configure the starlight integration to include your component. Add a components field, containing a Search key, mapping to the relative path to your component.

astro.config.mjs
import { defineConfig } from 'astro/config'
import starlight from '@astrojs/starlight'
export default defineConfig({
integrations: [
starlight({
title: 'My Docs with Overrides',
components: {
// Override the default `Search` component.
Search: './src/components/Search.astro'
}
})
]
})

Wrapping up

And that’s it! A working Docsearch widget in Starlight. There are more ways to extend and improve this. For example. one thing I haven’t covered here is UI translations. Docsearch does have support for translations, and it’s relatively simple to add, so if you have multi-lingual documentation, be sure to check the Docsearch translation reference.