Build Webhooks using Javascript and Next.js (Sample App) August 2021 · ian
Introduction
If you are a Javascript developer that uses React and Next.js, then this article is for you. Today we are going to walk through what it takes to add webhooks to a Next.js application. To help with this we have open sourced the code, so you can go ahead and clone it to follow along. Additionally there is a live demo to see the finished project in action.
For this sample webhook app we are going to be building a Todo app. We wanted to pick something that would trigger lots of different types of events and isn’t overly complicated to build.
We hope you enjoy it and let us know if you have any questions or feedback!
Getting Started
Resources
Here are some additional resources that you may need before we get started:
To integrate the NextJs demo app with the HostedHooks webhook service you will need to start by creating a HostedHooks account. It will only take a few minutes and then we can get started on the fun part.
Step 1: Create an account
Start by heading over to www.hostedhooks.com/sign_up and create an account. You will be prompted to set up your organization.
Step 2: Create your app
Next you will need to create an app within the HostedHooks dashboard. This app is where your webhooks will be sent from. Generate that app by clicking on “Setup New App” and entering your App name, something like “NextJS Demo” would work.
We have more documentation here
Step 3. Create a Webhook Event for your app instance
Next, go to your app and create a Webhook Event for your app that subscribers can subscribe to.
For this demo app, we’ve created 4 events based on a traditional todo app:
- todo.created - triggered whenever a new todo is created
- todo.completed - triggered whenever a todo is completed
- todo.uncompleted - triggered whenever a todo is uncompleted
- todo.deleted - triggered whenever a todo is deleted
Note: The events being sent from your application must match the events created in your app instance and they must be created first.
Once your webhook events are generated, we are all set to get started on the Next.js part of the demo.
Next.js Todo App
Now let’s jump into the code.
You can either clone the repo that we open sourced or you can start fresh with a clean Next.js app.
Note: We won’t cover the Next.js basics here as those are well documented on lots of other sites.
Environment Variables
In order for your Next.js app to speak to HostedHooks and send webhooks, you will need to add two variables to your environment.
Start by copying the .env.local.example file in your root directory to .env.local (which will be ignored by Git)
These two environment variables are:
NEXT_PUBLIC_HOSTEDHOOKS_API_KEY is the API Key from your account settings.
NEXT_PUBLIC_APP_UUID is the ID of your app instance.
Your APIKEY will be in your account settings, copy and paste that into your .env file. Your APPUUID can be found and copied on your HostedHooks app page. Copy that id and paste it into your .env file.
Running in dev mode
Once your environment variables are in place start your dev environment with either the npm or yarn commands below.
$ npm install
$ npm run dev
# or
$ yarn install
$ yarn dev
Your app should now be running at http://localhost:3000
The code
There are two parts of the integration, the first is triggering events and the second is sending those events.
In this case of this Todo app, we are going to be triggering events on the front end whenever one of these four events occur:
- todo.created - triggered whenever a new todo is created
- todo.completed - triggered whenever a todo is completed
- todo.uncompleted - triggered whenever a todo is uncompleted
- todo.deleted - triggered whenever a todo is deleted
To handle this we’ll use an event handler where we pass the id of the object to call a sendWebhookMessage
function. This function will be doing the heavy lifting of interacting with the HostedHooks API.
Let’s look at the code that triggers the event.
Triggering an event:
When your app triggers an event, you can send a webhook message by calling your webhook function:
const handleOnDeleteTodoClick = (id) => {
// deleting todo locally, you may want to call an API
const todo = deleteTodo(id);
// you can pass in whatever data you want to send with the event
sendWebhookMessage('todo.deleted', todo);
};
Once the event has been triggered, it will pass all of the respective object data to the sendWebhookMessage function along with the event that was triggered. The object and it’s data will be used to build the custom data payload that will be sent in the webhook message.
Let’s look at the webhook message.
Building your webhook message:
In your webhook message, you can form the data object as you want:
export default function sendWebhookMessage(event, todo) {
var url = new URL(
`https://www.hostedhooks.com/api/v1/apps/${process.env.NEXT_PUBLIC_APP_UUID}/messages`
);
// message headers
var myHeaders = new Headers();
myHeaders.append('Authorization', `Bearer ${process.env.NEXT_PUBLIC_HOSTEDHOOKS_API_KEY}`);
myHeaders.append('Content-Type', 'application/json');
// data to be sent with an event, ex: user session data
const user = {
id: 'user_id',
role: 'team_manager',
};
// webhook message
var messagePayload = JSON.stringify({
data: {
user: user,
todo: todo, // todo data
},
version: '1.0',
event_type: event, // `todo.deleted`
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: messagePayload,
redirect: 'follow',
};
fetch(url, requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.error(error));
}
The payload for the webhook message API call is very simple, let’s cover all the attributes:
var messagePayload = JSON.stringify({
data: {
user: user,
todo: todo, // todo data
},
version: '1.0',
event_type: event, // `todo.deleted`
});
- Data object: This is your custom payload and the information that will be passed on to your webhook subscribers
- Version: This is the version of the payload that you want to send. You can build different versions of your payloads without breaking your existing subscribers integrations.
- Event type: This is the webhook event that was triggered. This is how we determine who should receive the webhook message.
Testing your webhooks
Now your app is ready to go. You can delete, complete, update or create a new todo, and open your devtools to see the result.
You should get a 201 Created success status response code which indicates that your webhook message has been sent, and your subscribers have been notified. We can also see inside your HostedHooks dashboard that the messages are being received from the Next.js demo app. If you open the App that we created at the beginning of this demo you will see messages at the bottom of your app page. These are the messages being triggered by the front end app
We can go ahead and create a mock subscriber to simulate the end to end flow of webhook messages from the ToDo app -> HostedHooks -> Mock Subscriber endpoint. This gif is showing us creating a "test" todo on the todo app, which is being sent to the HostedHooks API, routed to a subscriber we created and delivering a webhook to an endpoint we created.
Demo Site
To help with this walkthrough we have hosted the open-sourced NextJs webhooks ToDo app so you can view it in action. See it live here - https://nextjs-hostedhooks-demo.herokuapp.com/
Follow Us
You can follow us @hostedhooks or sign up below to receive our updates.
Try HostedHooks Free
Getting started is easy! No credit card required.