How to verify and process webhook notifications in Next.js
Processing webhook notifications is now possible directly within your Next.js website implementation. How can you create an API route and use it to verify and process a webhook from Kontent.ai?
In this article, I will explain what webhooks are used for, show how to process them, and verify their source in Next.js.
What is a webhook notification?
Webhook is simply an HTTP request—a notification whenever something happens. Let’s say you publish a new content item. Then, you may need to rebuild your site, update a search index, or tweet about the new content on Twitter. The code that handles these use cases is invoked by the webhook notification issued by Kontent.ai.
How are webhooks secured?
The webhook notification travels through the internet to a defined destination—that’s where you deployed your code. The code needs to be publicly available, so you should always check the webhook origin by analyzing the request signature.
The signature is a hash of the request payload and your chosen secret that you can configure in Kontent.ai. Whenever a webhook gets dispatched, Kontent.ai will calculate the hash and assign it the X-KC-Signature header value. In your code, you should do the same and check that the signatures match.
Implementing the signature check
Let’s see how we can do that in Next.js. First, we’ll add the API route to the Next.js site. Create a new file update.ts under /pages/api and add the following:
The request payload in raw form We need the raw body as every whitespace changes the output of the hash function. And that’s a bit tricky as Next.js automatically parses the body for every API request.
The library will allow us to get the raw body as a string. Typically, we also want to work with the data in the body, so we’ll also parse the body using JSON.parse:
import { buffer } from 'micro'
export default async (req: NextApiRequest, res: NextApiResponse) {
const body = (await buffer(req)).toString()
const data = JSON.parse(body)
}
...
What if we told you there was a way to make your website a place that will always be relevant, no matter the season or the year? Two words—evergreen content. What does evergreen mean in marketing, and how do you make evergreen content? Let’s dive into it.
How can you create a cohesive experience for customers no matter what channel they’re on or what device they’re using? The answer is going omnichannel.
To structure a blog post, start with a strong headline, write a clear introduction, and break content into short paragraphs. Use descriptive subheadings, add visuals, and format for easy scanning. Don’t forget about linking and filling out the metadata. Want to go into more detail? Dive into this blog.
Lucie Simonova
Subscribe to the Kontent.ai newsletter
Get the hottest updates while they’re fresh! For more industry insights, follow our LinkedIn profile.