Easily restore your project to a previous version with our new Instant One-click Backup Recovery

Sync Content to Algolia with Hygraph Webhooks

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

Jamie Barton

Sep 08, 2020
Sync Content to Algolia from Hygraph using Webhooks

One of the most common use cases when using Hygraph webhooks we often see users exploring is syncing Hygraph 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.

Hygraph 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](https://codesandbox.io/s/github/hygraph/hygraph-examples/tree/master/with-algolia)

![Deploy with Vercel](https://vercel.com/import/project?template=https://github.com/hygraph/hygraph-examples/tree/master/with-algolia)

Blog Author

Jamie Barton

Jamie Barton

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 currently publishes Weekly GraphQL Screencasts.