JAVASCRIPT

Building a Simple Webhook Listener with Express

Create a robust Node.js Express server to reliably receive and process real-time data payloads from third-party API webhooks.

const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto'); // For verifying signatures

const app = express();
const PORT = process.env.PORT || 3000;
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || 'your_super_secret_key'; // Store securely!

// Middleware to parse JSON bodies. Must be placed BEFORE webhook routes.
app.use(bodyParser.json({
    verify: (req, res, buf) => {
        // Store the raw body for signature verification
        req.rawBody = buf;
    }
}));

// Webhook endpoint
app.post('/webhook', (req, res) => {
    const signature = req.headers['x-webhook-signature']; // Common header for signatures

    // Optional: Verify webhook signature for security
    if (signature) {
        const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
        hmac.update(req.rawBody);
        const digest = `sha256=${hmac.digest('hex')}`;
        if (signature !== digest) {
            console.warn('Webhook signature mismatch. Request potentially forged.');
            return res.status(403).send('Invalid signature');
        }
    } else {
        console.warn('Webhook received without signature. Proceeding with caution.');
    }

    const event = req.body;
    console.log('Received webhook event:', event.type);
    // console.log('Payload:', event); // Uncomment to see full payload

    // Process the event asynchronously to avoid blocking the webhook sender
    // In a real application, you'd push this to a queue (e.g., Redis, Kafka)
    // or a background job processor.
    processWebhookEvent(event)
        .then(() => {
            res.status(200).send('Event received and acknowledged');
        })
        .catch(error => {
            console.error('Error processing webhook event:', error);
            res.status(500).send('Internal Server Error');
        });
});

async function processWebhookEvent(event) {
    // Simulate asynchronous processing, e.g., saving to DB, triggering other services
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(`Successfully processed event ID: ${event.id || 'N/A'}`);
            resolve();
        }, 100);
    });
}

// Basic health check endpoint
app.get('/', (req, res) => {
    res.send('Webhook Listener is running!');
});

app.listen(PORT, () => {
    console.log(`Webhook listener running on port ${PORT}`);
});
How it works: This Node.js Express snippet sets up a simple server to act as a webhook listener. It's designed to receive POST requests from external APIs, parse their JSON payloads, and optionally verify request signatures to ensure authenticity. The `processWebhookEvent` function simulates asynchronous handling of the received data, which is crucial for not blocking the sender and promptly acknowledging receipt.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs