JAVASCRIPT
Creating a Node.js Webhook Endpoint with Express for API Push Notifications
Set up a robust webhook endpoint in Node.js using Express to securely receive and process real-time push notifications from third-party APIs.
const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto'); // For signature verification
const app = express();
const PORT = process.env.PORT || 3000;
const WEBHOOK_SECRET = 'your_super_secret_key'; // Keep this secure and from environment variables
// Use raw body parser for signature verification
app.use(bodyParser.json({
verify: (req, res, buf) => {
req.rawBody = buf; // Store the raw body for signature verification
}
}));
// Webhook endpoint
app.post('/webhook/data-update', (req, res) => {
const signature = req.headers['x-signature'] || req.headers['webhook-signature']; // Common header names
// IMPORTANT: Implement signature verification for security
if (WEBHOOK_SECRET && signature) {
const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
hmac.update(req.rawBody); // Use the raw body for HMAC calculation
const digest = 'sha256=' + hmac.digest('hex');
if (digest !== signature) {
console.warn('Webhook signature mismatch. Request likely unauthorized or tampered with.');
return res.status(403).send('Invalid signature');
}
} else if (WEBHOOK_SECRET && !signature) {
console.warn('Webhook secret configured but no signature found. Rejecting for security.');
return res.status(403).send('Missing signature');
}
console.log('Received webhook notification!');
console.log('Payload:', req.body); // The parsed JSON payload
// Process the payload here, e.g., update database, trigger other services
// Example:
// if (req.body.eventType === 'order.created') {
// console.log('New order created:', req.body.data.orderId);
// // Call order processing logic
// }
res.status(200).send('Webhook received successfully');
});
// Basic route for health check
app.get('/', (req, res) => {
res.send('Webhook server is running.');
});
app.listen(PORT, () => {
console.log(`Webhook server listening on port ${PORT}`);
console.log(`Endpoint: http://localhost:${PORT}/webhook/data-update`);
});
How it works: This Node.js snippet uses the Express framework to create a server-side webhook endpoint. Webhooks allow third-party APIs to push real-time notifications to your application when certain events occur (e.g., a payment processed, a new user registered). The snippet shows how to set up a POST route, parse the incoming JSON payload, and critically, how to implement signature verification using HMAC-SHA256 to ensure the request genuinely originated from the trusted API and hasn't been tampered with. This is crucial for securing webhook endpoints.