Blogs
Understanding Webhooks in Node.js & Express - Real World Implementation Guide
Learn what webhooks are and how to implement them in Express.js and Node.js. This complete guide covers webhook concepts, real-world use cases, security verification, testing with ngrok, and best practices with step-by-step implementation examples.
%2520(3).jpg%3Falt%3Dmedia%26token%3Df9d0fc58-063f-4da6-aaa5-5f137ba8a556&w=1080&q=75)
Webhooks in Express.js - Complete Guide with Implementation
Modern applications constantly need to communicate with each other in real time. For example:
Payment confirmation from a payment gateway
GitHub notifying when code is pushed
Stripe informing when a payment succeeds
Shopify notifying when an order is created
Instead of repeatedly asking another server “Did something happen?”, applications use Webhooks.
In this guide we will learn:
What Webhooks are
Why Webhooks are used
Webhooks vs APIs
How Webhooks work
How to implement Webhooks in Express.js
Security considerations
Testing Webhooks
Best practices
Real-world examples
1. What is a Webhook?
A Webhook is an HTTP callback triggered by an event.
When an event occurs in one system, it sends an HTTP request to another server automatically.
In simple terms:
A webhook is a way for one application to send real-time data to another application when an event happens.
Example
A payment gateway sends a request to your server when a payment succeeds.
User pays → Payment gateway → Webhook → Your server updates order status2. Why Do We Use Webhooks?
Before webhooks, systems used Polling.
Polling (Bad approach)
Did payment succeed?
Did payment succeed?
Did payment succeed?
Example:
GET /payment-statusProblems with polling:
Wastes server resources
Delayed responses
More API calls
Inefficient
Webhooks (Better approach)
Payment success → Payment gateway sends request → Your serverReal-time updates
No unnecessary requests
Efficient communication
Event-driven architecture
3. Webhook vs API
Example:
API
GET /ordersWebhook
POST /webhook/order-created4. How Webhooks Work
Your server registers a webhook URL
External service stores this URL
When event occurs → service sends HTTP POST request
Your server receives data
Your server processes event
Flow Diagram
Service A (Stripe, GitHub)
│
│ Event happens
▼
HTTP POST Request
▼
Webhook URL on Your Server
▼
Express Server Processes Event
5. Implementing Webhooks in Express.js
Step 1 - Setup Express Project
npm init -ynpm install expressserver.jsStep 2 - Basic Express Server
const express = require("express");
const app = express();
app.use(express.json());
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Step 3 - Create Webhook Endpoint
app.post("/webhook/payment", (req, res) => {
const event = req.body;
console.log("Webhook received:", event);
if (event.type === "payment_success") {
console.log("Payment completed for user:", event.userId);
}
res.status(200).send("Webhook received");
});
POST http://your-server.com/webhook/paymentExample Webhook Payload
{
"type": "payment_success",
"amount": 2000,
"currency": "USD",
"userId": "user123"
}
req.body6. Simulating a Webhook
curl -X POST http://localhost:3000/webhook/payment \
-H "Content-Type: application/json" \
-d '{
"type":"payment_success",
"amount":2000,
"userId":"123"
}'
Webhook received
Payment completed for user: 123
7. Real World Example - GitHub Webhook
{
"ref": "refs/heads/main",
"repository": {
"name": "my-project"
},
"pusher": {
"name": "developer"
}
}
app.post("/webhook/github", (req, res) => {
const payload = req.body;
console.log(`New push in repo ${payload.repository.name}`);
console.log(`Pushed by ${payload.pusher.name}`);
res.sendStatus(200);
});
8. Webhook Security (Very Important)
1. Secret Signature Verification
X-Signature: abc123const crypto = require("crypto");
function verifySignature(payload, signature, secret) {
const hash = crypto
.createHmac("sha256", secret)
.update(JSON.stringify(payload))
.digest("hex");
return hash === signature;
}
2. IP Whitelisting
Stripe webhook IP ranges
GitHub webhook IP ranges
3. HTTPS Only
https://9. Handling Webhook Failures
Retry after 5 seconds
Retry after 1 minute
Retry after 10 minutes
Always return HTTP 200 quickly
Process events asynchronously
app.post("/webhook", async (req, res) => {
res.sendStatus(200);
await processEvent(req.body);
});
10. Idempotency in Webhooks
if(eventAlreadyProcessed(event.id)){
return;
}
11. Queue Based Processing (Advanced)
Webhook → Queue → Worker → Database12. Logging Webhooks
console.log("Webhook event:", JSON.stringify(req.body));webhook_logs table13. Testing Webhooks Locally
ngrok
npm install -g ngrokngrok http 3000https://abc123.ngrok.io/webhook/payment14. Common Webhook Use Cases
Payment systems
payment_success
payment_failed
refund_processed
Git platforms
push
pull_request
release
E-commerce
order_created
order_paid
order_cancelled
15. Best Practices for Webhooks
Always verify signatures
Respond quickly
Process events asynchronously
Implement retries
Handle duplicate events
Use logging
Secure with HTTPS
Validate payload schema
Final Express Webhook Example
const express = require("express");
const crypto = require("crypto");
const app = express();
app.use(express.json());
const SECRET = "webhooksecret";
function verifySignature(payload, signature) {
const hash = crypto
.createHmac("sha256", SECRET)
.update(JSON.stringify(payload))
.digest("hex");
return hash === signature;
}
app.post("/webhook", (req, res) => {
const signature = req.headers["x-signature"];
if (!verifySignature(req.body, signature)) {
return res.status(401).send("Invalid signature");
}
console.log("Webhook received:", req.body);
res.status(200).send("Event processed");
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Conclusion
Webhooks enable real-time communication between systems.
Create an endpoint
Receive POST requests
Validate the request
Process event
Respond quickly
With these best practices, you can build reliable webhook systems in Node.js and Express.



