codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🟢

Node.js

48 / 63 topics
46GraphQL with Node.js47Apollo Server48Webhooks
Tutorials/Node.js/Webhooks
🟢Node.js

Webhooks

Updated 2026-05-15
10 min read

Webhooks

Introduction

In this section, we will explore the concept of webhooks and how to implement them in Node.js applications. Webhooks are a powerful tool for real-time communication between different services or platforms. They allow one application to send notifications or data to another application as soon as something happens.

For example, GitHub can notify your application whenever there is a new commit pushed to a repository. Similarly, Stripe can notify your application about payment events. Understanding and implementing webhooks can greatly enhance the interactivity and functionality of your Node.js applications.

Concept

A webhook is essentially an HTTP callback that allows one application to send real-time data to another application. When a specific event occurs in the source application (like a new commit, a payment being made, etc.), it sends an HTTP POST request to a predefined URL (the webhook endpoint) with the relevant data.

The receiving application can then process this data and perform actions based on the event. This is particularly useful for integrating different services or building applications that need to react to external events in real-time.

Examples

Setting Up a Basic Webhook in Node.js

Let's walk through an example of setting up a basic webhook server using Express.js, a popular web framework for Node.js.

Step 1: Install Dependencies

First, you need to set up a new Node.js project and install the necessary dependencies. Open your terminal and run:

Terminal
$ mkdir webhook-example
$ cd webhook-example
$ npm init -y
$ npm install express body-parser

Step 2: Create the Webhook Server

Create a file named server.js in your project directory and add the following code:

JavaScript
1const express = require('express');
2const bodyParser = require('body-parser');
3
4const app = express();
5const PORT = process.env.PORT || 3000;
6
7// Middleware to parse JSON bodies
8app.use(bodyParser.json());
9
10// Define a webhook endpoint
11app.post('/webhook', (req, res) => {
12 const event = req.body.event;
13 const data = req.body.data;
14
15 console.log('Received event:', event);
16 console.log('Event data:', data);
17
18 // Process the event and send a response
19 res.status(200).send('Webhook received');
20});
21
22app.listen(PORT, () => {
23 console.log(`Server is running on port ${PORT}`);
24});

Step 3: Test the Webhook

To test your webhook server, you can use a tool like Postman or cURL. Here's how you can do it using cURL:

Terminal
$ curl -X POST http://localhost:3000/webhook -H "Content-Type: application/json" -d '{
"event": "new_commit",
"data": {
"repository": "my-repo",
"commit_hash": "abc123"
}
}'

You should see the following output in your terminal:

Output
Server is running on port 3000
Received event: new_commit
Event data: { repository: 'my-repo', commit_hash: 'abc123' }
Webhook received

Securing Webhooks

In a production environment, it's crucial to secure your webhooks to prevent unauthorized access. One common method is to use a secret token that both the sender and receiver agree upon.

Step 1: Modify the Server Code

Update your server.js file to include a secret token for verification:

JavaScript
1const express = require('express');
2const bodyParser = require('body-parser');
3
4const app = express();
5const PORT = process.env.PORT || 3000;
6const SECRET_TOKEN = 'your_secret_token';
7
8// Middleware to parse JSON bodies
9app.use(bodyParser.json());
10
11// Define a webhook endpoint with token verification
12app.post('/webhook', (req, res) => {
13 const event = req.body.event;
14 const data = req.body.data;
15 const token = req.headers['x-webhook-token'];
16
17 if (token !== SECRET_TOKEN) {
18 return res.status(401).send('Unauthorized');
19 }
20
21 console.log('Received event:', event);
22 console.log('Event data:', data);
23
24 // Process the event and send a response
25 res.status(200).send('Webhook received');
26});
27
28app.listen(PORT, () => {
29 console.log(`Server is running on port ${PORT}`);
30});

Step 2: Test with Token

When sending a webhook request now, include the x-webhook-token header:

Terminal
$ curl -X POST http://localhost:3000/webhook -H "Content-Type: application/json" -H "x-webhook-token: your_secret_token" -d '{
"event": "new_commit",
"data": {
"repository": "my-repo",
"commit_hash": "abc123"
}
}'

Handling Different Events

You can extend your webhook server to handle different types of events by adding conditional logic based on the event type.

Step 1: Update the Server Code

Modify your server.js file to handle multiple event types:

JavaScript
1const express = require('express');
2const bodyParser = require('body-parser');
3
4const app = express();
5const PORT = process.env.PORT || 3000;
6const SECRET_TOKEN = 'your_secret_token';
7
8// Middleware to parse JSON bodies
9app.use(bodyParser.json());
10
11// Define a webhook endpoint with token verification and event handling
12app.post('/webhook', (req, res) => {
13 const event = req.body.event;
14 const data = req.body.data;
15 const token = req.headers['x-webhook-token'];
16
17 if (token !== SECRET_TOKEN) {
18 return res.status(401).send('Unauthorized');
19 }
20
21 switch (event) {
22 case 'new_commit':
23 console.log('Handling new commit event:', data);
24 // Add your logic for handling new commits
25 break;
26 case 'payment_received':
27 console.log('Handling payment received event:', data);
28 // Add your logic for handling payments
29 break;
30 default:
31 console.log('Unhandled event:', event);
32 }
33
34 res.status(200).send('Webhook received');
35});
36
37app.listen(PORT, () => {
38 console.log(`Server is running on port ${PORT}`);
39});

What's Next?

In the next section, we will explore CI/CD Pipelines and how to automate your deployment processes using tools like Jenkins, GitHub Actions, or GitLab CI. This will help you streamline your development workflow and ensure that your applications are deployed consistently and reliably.

By understanding and implementing webhooks in Node.js, you can build more interactive and responsive applications that can react to external events in real-time.


PreviousApollo ServerNext CI/CD Pipelines

Recommended Gear

Apollo ServerCI/CD Pipelines