JAVASCRIPT
Create a Simple Webhook Listener with Node.js and Express
Set up a basic webhook endpoint in Node.js using Express to receive and process real-time events from external services like GitHub or Stripe.
const express = require('express');
const bodyParser = require('body-parser'); // For parsing incoming request bodies
const crypto = require('crypto'); // For verifying webhook signatures
const app = express();
const PORT = process.env.PORT || 3000;
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || 'your-super-secret-key'; // Shared secret for signature verification
// Use body-parser to parse JSON bodies. IMPORTANT: raw body is needed for signature verification
app.use(bodyParser.json({
verify: (req, res, buf) => {
req.rawBody = buf; // Make the raw body available for signature verification
}
}));
// Webhook endpoint
app.post('/webhook', (req, res) => {
// --- Optional: Verify webhook signature (highly recommended for production) ---
// Example for GitHub-like HMAC-SHA256 signature
const signature = req.headers['x-hub-signature-256'] || req.headers['x-webhook-signature'];
if (signature) {
const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
const digest = 'sha256=' + hmac.update(req.rawBody).digest('hex');
if (signature !== digest) {
console.warn('Webhook signature mismatch! Request potentially unauthorized.');
return res.status(401).send('Signature mismatch');
}
console.log('Webhook signature verified successfully.');
} else {
console.warn('No webhook signature provided. Proceeding without verification (NOT recommended for sensitive data).');
}
// --- Process the webhook payload ---
const eventType = req.headers['x-github-event'] || 'unknown_event'; // Example for GitHub
const payload = req.body;
console.log(`Received ${eventType} event:`, payload);
// In a real application, you would typically:
// - Save the event to a database
// - Queue a job for asynchronous processing (e.g., using a message queue like RabbitMQ or Kafka)
// - Trigger other internal services or notifications
res.status(200).send('Webhook received and processed');
});
// Basic health check
app.get('/', (req, res) => {
res.send('Webhook listener is running.');
});
app.listen(PORT, () => {
console.log(`Webhook listener running on http://localhost:${PORT}`);
});
How it works: This snippet demonstrates how to set up a basic webhook listener using Node.js with the Express framework. Webhooks allow external services to send real-time event notifications to your application. The code defines a `POST` endpoint `/webhook` that receives incoming payloads. Crucially, it includes an optional but highly recommended section for verifying the webhook's signature using a shared secret, ensuring the request genuinely originated from the trusted source and hasn't been tampered with.