loading...

How to setup Algolia's DocSearch in NextJS app

estevanmaito profile image Estevan Maito ・1 min read

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 (
      <Html>
        <Head>
          <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.css"
          />
          <script
            type="text/javascript"
            src="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.js"></script>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

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) {
    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.

Posted on by:

estevanmaito profile

Estevan Maito

@estevanmaito

Full stack developer looking for what makes a great design. Follow my journey https://twitter.com/estevanmaito

Discussion

pic
Editor guide