JAVASCRIPT

Secure Webhook Handling with Signature Verification in Express

Learn to securely receive and verify webhook payloads in an Express.js application by computing and comparing request signatures, protecting against tampering.

// Make sure to install express: npm install express
// And install body-parser for raw body access: npm install body-parser
const express = require('express');
const crypto = require('crypto');
const bodyParser = require('body-parser'); // Required to get raw body for signature verification

const app = express();
const port = 3000;

// IMPORTANT: Use a raw body parser for webhook routes that need signature verification
// This makes the raw request body available on req.rawBody
app.use('/webhook-listener', bodyParser.raw({ type: 'application/json' }));

// Your secret key for verifying webhooks. This should be a strong, random string.
// Store this securely, e.g., in environment variables.
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || 'your_super_secret_webhook_key';

// Middleware to verify webhook signatures
function verifyWebhookSignature(req, res, next) {
    // Example: GitHub webhooks typically send a 'x-hub-signature-256' header
    // Different services use different headers (e.g., Stripe uses 'stripe-signature')
    const signatureHeader = req.headers['x-hub-signature-256'];
    if (!signatureHeader) {
        console.warn('Webhook received without signature header.');
        return res.status(401).send('Unauthorized: Signature missing');
    }

    // GitHub's signature format: `sha256=<signature>`
    const signature = signatureHeader.split('=')[1];
    if (!signature) {
        console.warn('Malformed signature header.');
        return res.status(401).send('Unauthorized: Malformed signature');
    }

    // The raw body is needed to compute the HMAC.
    // If req.rawBody is undefined, bodyParser.raw was not used correctly for this route.
    if (!req.rawBody) {
        console.error('req.rawBody is missing. Ensure bodyParser.raw is used.');
        return res.status(500).send('Internal Server Error: Raw body not available.');
    }

    const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
    hmac.update(req.rawBody);
    const digest = hmac.digest('hex');

    if (crypto.timingSafeEqual(Buffer.from(digest), Buffer.from(signature))) {
        // Signature is valid. Parse the JSON body for further processing.
        // Note: req.body will still be a Buffer from bodyParser.raw.
        // So, parse it explicitly or use another middleware *after* verification.
        try {
            req.body = JSON.parse(req.rawBody.toString('utf8'));
            console.log('Webhook signature verified successfully!');
            next();
        } catch (e) {
            console.error('Failed to parse webhook body after verification:', e);
            res.status(400).send('Bad Request: Invalid JSON body');
        }
    } else {
        console.warn('Webhook signature verification failed.');
        res.status(403).send('Forbidden: Invalid signature');
    }
}

// Webhook listener endpoint
app.post('/webhook-listener', verifyWebhookSignature, (req, res) => {
    // If we reach here, the signature is valid and req.body contains the parsed JSON payload.
    console.log('Received verified webhook payload:', req.body);
    // Process the payload (e.g., update database, trigger other services)
    res.status(200).send('Webhook received and processed.');
});

app.get('/', (req, res) => {
    res.send('Webhook server is running. POST to /webhook-listener');
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
    console.log(`Webhook secret: ${WEBHOOK_SECRET.substring(0, 5)}...`);
});
How it works: This Express.js snippet demonstrates how to securely handle incoming webhooks by verifying their signatures. Many external services include a signature in the request headers, generated using a shared secret and the request body. The `verifyWebhookSignature` middleware computes its own HMAC (Hash-based Message Authentication Code) from the raw request body and the `WEBHOOK_SECRET`. It then performs a timing-safe comparison with the signature provided by the webhook sender. This process ensures that the payload originated from the legitimate service and has not been tampered with in transit, preventing unauthorized or malicious requests from being processed by your application. The `bodyParser.raw` middleware is crucial here as it provides access to the unparsed, raw request body, which is required for accurate signature calculation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs