DEV Community 👩‍💻👨‍💻

Estevan Maito
Estevan Maito

Posted on

How to setup Algolia's DocSearch in NextJS app

I've spent some time figuring out why my search wasn't working, just to realize that Algolia's documentation was meant to be used in a common HTML approach. In the end, the app was loading before the script was initilized.

TL;DR: If you're not using Next JS, just ignore the first step and add the script and the styles to your root html (usually index.html) and initialize it like the last snippet inside the component.

With NextJS, you need to create a file named _document.js inside pages (the minimum setup can be found in Next's documentation), and add the CSS and Docsearch script to the Head. This way the search will be accessible through all the pages.

import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }

  render() {
    return (
          <Main />
          <NextScript />

export default MyDocument

Then, in your component (in my case Navbar.jsx), initialize the script that you've received, inside componentDidMount or useEffect.

useEffect(() => {
  if (window.docsearch) {
      apiKey: 'your api',
      indexName: 'your id',
      inputSelector: '#algolia-search', // the selector of my search input
  } else {
    console.warn('Search has failed to load')
    // do something here
}, [])

I hope that this save people some time when implementing Docsearch.

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.