Algolia and Next.js - Index Updates and getStaticProps Side Effects

Viewed 713

I've got a fairly complex Next.js site that is mostly statically rendered and I'm adding Algolia search into the site. The mechanics of Algolia require that you use their API and notify them of additional content every time it gets published.

My question is where in the Next app you notify Algolia. Given that my site is using getStaticProps to fetch data, I figured this is the logical place to notify and update Algolia. It works but wondering what others have done, best practice, tradeoffs, etc.

The lifecycle looks like this:

  • Get data from database via GraphQL (using headless CMS Prismic)
  • Normalize data inside Next before sending to Algolia
  • Send data to Algolia (their system reconciles old/new records be referencing uuid)

Code that makes this happen:

// Use nextjs getStaticProps, destructure default params
export async function getStaticProps({ params, preview = false, previewData }) {
        
  // Data fetch (assume getAllNewsForLandingPage gets an array of obj)
  pageData.data = await getAllNewsForLandingPage(params.uid, previewData)

  // Format and normalize results
  const algoliaFormattedData = dataFormatter(pageData.data)

  // Send data back to Algolia, who will reconcile old and new data automatically
  await AlgoliaIndex.saveObjects(algoliaFormattedData)
}
0 Answers
Related