JAVASCRIPT

Set Up a Basic Webhook Receiver with Node.js Express

Create a simple backend endpoint in Node.js with Express to reliably receive and process webhook notifications from external services, enabling real-time data updates.

const express = require('express');
const bodyParser = require('body-parser'); // To parse JSON bodies
const crypto = require('crypto'); // For signature verification

const app = express();
const port = 3000;
const WEBHOOK_SECRET = 'your_super_secret_webhook_key'; // Replace with a strong, secret key

// Middleware to parse JSON bodies
app.use(bodyParser.json());

// Basic authentication middleware (optional, but highly recommended for webhooks)
// This example uses a shared secret in a custom header or body, a real implementation
// might use a more robust signature verification (e.g., HMAC-SHA256)
function verifyWebhookSignature(req, res, next) {
  const signature = req.headers['x-webhook-signature']; // Example header
  // For services that send HMAC signature:
  // const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
  // hmac.update(JSON.stringify(req.body));
  // const digest = 'sha256=' + hmac.digest('hex');

  // Simple shared secret check (less secure, use signature verification if possible)
  if (signature === WEBHOOK_SECRET) { // Or compare `digest` if using HMAC
    next(); // Signature valid, proceed to handler
  } else {
    console.warn('Webhook signature mismatch or missing.');
    res.status(403).send('Forbidden: Invalid webhook signature');
  }
}

// Webhook endpoint
app.post('/webhook/data-update', verifyWebhookSignature, (req, res) => {
  console.log('Received webhook notification!');
  const eventData = req.body; // The data sent by the webhook
  console.log('Event data:', eventData);

  // Process the event data here
  // For example: update a database, send an email, trigger another process.
  // Make sure to respond quickly to avoid webhook provider timeouts.
  // Asynchronous tasks can be handled after responding.
  processWebhookAsync(eventData); // Example async processing

  res.status(200).send('Webhook received and acknowledged.');
});

async function processWebhookAsync(data) {
  console.log('Asynchronously processing webhook data...');
  // Simulate a long-running task
  await new Promise(resolve => setTimeout(resolve, 2000));
  console.log('Webhook data processed:', data);
  // Further actions like updating database, sending notifications, etc.
}

app.listen(port, () => {
  console.log(`Webhook receiver listening at http://localhost:${port}`);
  console.log(`Configure your external service to send POST requests to http://your-server-ip:${port}/webhook/data-update`);
});
How it works: This Node.js snippet sets up a basic webhook receiver using the Express framework. A webhook is a method for one application to provide other applications with real-time information as it happens, rather than periodically polling for updates. This server defines a `POST` endpoint (`/webhook/data-update`) that listens for incoming data. It includes a `bodyParser` to handle JSON payloads and a `verifyWebhookSignature` middleware (with a simple example and a note on more robust HMAC verification) to authenticate the sender, enhancing security. Upon receiving a valid webhook, it logs the data and can trigger asynchronous processing, ensuring the server responds quickly to the webhook provider to avoid timeouts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs