Sync content to Algolia with GraphCMS webhooks

Jamie Barton
Jamie Barton

September 8, 2020

Sync content to Algolia with GraphCMS 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, } = PUBLISHED;
await index.saveObject({ objectID, });
} catch (err) {

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

It's Easy To Get Started

GraphCMS plans are flexibly suited to accommodate your growth. Get started for free, or reach out to our sales team to discuss larger projects with more complex needs