JAVASCRIPT

Create a Basic Webhook Receiver Endpoint with Express.js (Node.js)

Learn to set up a simple HTTP endpoint in Node.js using Express.js to receive and process webhook payloads from third-party services.

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const PORT = process.env.PORT || 3000;

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

// Middleware to parse URL-encoded bodies (if your webhooks send form data)
// app.use(bodyParser.urlencoded({ extended: true }));

// Webhook receiver endpoint
app.post('/webhook', (req, res) => {
  console.log('Received Webhook Payload:');
  console.log('Headers:', req.headers); // Log all headers for debugging
  console.log('Body:', req.body); // The parsed JSON payload

  // IMPORTANT: Validate the webhook source and signature
  // For example, if from GitHub, check `X-Hub-Signature` header
  // if (!isValidSignature(req.headers['x-hub-signature'], req.body)) {
  //   return res.status(403).send('Invalid signature');
  // }

  // Process the webhook payload here
  // e.g., save to database, trigger another service, send notifications
  if (req.body && req.body.event_type) {
    console.log(`Processing event type: ${req.body.event_type}`);
    // Further logic based on event_type
  } else {
    console.log('Webhook body has no specific event_type.');
  }

  // Respond quickly to acknowledge receipt
  res.status(200).send('Webhook received successfully!');
});

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

// Start the server
app.listen(PORT, () => {
  console.log(`Webhook receiver listening on port ${PORT}`);
  console.log(`Access at: http://localhost:${PORT}`);
  console.log(`Webhook endpoint: http://localhost:${PORT}/webhook`);
});

// Placeholder for signature validation function (implement based on provider's docs)
// function isValidSignature(signature, payload) {
//   // Example: For GitHub, calculate HMAC SHA1 hash of payload with secret
//   // const crypto = require('crypto');
//   // const hmac = crypto.createHmac('sha1', 'YOUR_WEBHOOK_SECRET');
//   // hmac.update(JSON.stringify(payload));
//   // const digest = 'sha1=' + hmac.digest('hex');
//   // return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(digest));
//   return true; // For demonstration, bypass signature validation
// }
How it works: This Node.js snippet provides a basic setup for an HTTP endpoint using Express.js to act as a webhook receiver. Webhooks are automated messages sent from applications when an event occurs, typically via an HTTP POST request. This code uses `body-parser` to automatically parse incoming JSON payloads, logs the received data, and sends a quick 200 OK response to acknowledge receipt. It also includes comments highlighting the critical importance of validating webhook signatures for security in a production environment.

Need help integrating this into your project?

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

Hire DigitalCodeLabs