Content Modeling Best Practices
This post will help you learn some effective strategies for modeling structured content and give teams a look at how to build a well functioning structured content hub for a variety of project types.
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
This site uses cookies to provide you with a better user experience. For more information, refer to our Privacy Policy