Sync Content to Algolia with GraphCMS Webhooks

Get started with syncing published content to Algolia with GraphCMS webhooks, and Next.js API routes.

Jamie Barton
Jamie Barton
Sync Content to Algolia from GraphCMS using Webhooks

One of the most common use cases when using GraphCMS webhooks we often see users exploring is syncing GraphCMS data with a 3rd party service.

One service in particular is Algolia, which boasts a blazing fast search API, and a ready to go UI library for React, Vue, Angular, Vanilla JS, iOS, and Android.

GraphCMS boasts granular webhooks that give you the power to watch specific changes to data. In this example, I'm using a simple schema that contains products. I am watching for any new product drafts being promoted to the PUBLISHED stage.

When they do, we trigger a webhook to a Next.js API route, in this case /api/webhook.

The code in this webhook checks if the request is in fact a POST request, and has a Authorization header value that matches what we have record. If all is well, the rest of the serverless function is responsible for syncing data to Algolia.

Here is the serverless function:

const algoliasearch = require('algoliasearch');
const algolia = algoliasearch(process.env.NEXT_PUBLIC_ALGOLIA_APP_ID, process.env.ALGOLIA_ADMIN_API_KEY);
const index = algolia.initIndex('products');
export default async (req, res) => {
if (req.method !== 'POST') return res.end();
if (req.headers['authorization'] !== process.env.WEBHOOK_SECRET_KEY)
return res.status(401).end();
try {
const {
data: { PUBLISHED },
} = req.body;
const { id: objectID, ...data } = PUBLISHED;
await index.saveObject({ objectID, ...data });
res.send(201);
} catch (err) {
res.status(400).send(err?.message);
}
};

Once the function runs, content is immediately available to search using React Instant Search. You can see a demo here.

That's it! View the source code

Develop with Codesandbox

Deploy with Vercel


  • Jamie Barton
  • Developer Relations

    Jamie is a software engineer turned developer advocate. Born and bred in North East England, he loves learning and teaching others through video and written tutorials. Jamie maintains Build your DXP, Headless Commerce Resources, and GraphQL WTF.

Related articles

It's Easy To Get Started

GraphCMS plans are flexibly suited to accommodate your growth. Get started for free, or request a demo to discuss larger projects with more complex needs