JAVASCRIPT

Process and Route Incoming Webhook Events to Specific Handlers

Efficiently manage incoming webhook events by parsing the payload, identifying the event type, and routing it to the appropriate backend handler function using Node.js Express.

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

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

// Use raw body parser for webhooks to allow signature verification (if needed)
// For this example, we assume verification happens before or is not required.
app.use(bodyParser.json({ verify: (req, res, buf) => { req.rawBody = buf; } }));

// --- Webhook Handlers ---
const handleUserCreated = (eventData) => {
  console.log('User Created Event:', eventData);
  // Implement logic for user creation, e.g., create user in database, send welcome email
};

const handleOrderPaid = (eventData) => {
  console.log('Order Paid Event:', eventData);
  // Implement logic for order payment, e.g., update order status, notify shipping
};

const handleDefaultEvent = (eventData, eventType) => {
  console.log(`Unhandled Event Type '${eventType}':`, eventData);
  // Log unhandled events or send alerts
};

const eventHandlers = {
  'user.created': handleUserCreated,
  'order.paid': handleOrderPaid,
  // Add more event types and their respective handler functions
};

app.post('/webhook-receiver', (req, res) => {
  const event = req.body; // Assuming the webhook payload is JSON

  // Basic check for expected event structure
  if (!event || !event.type) {
    console.error('Invalid webhook payload: missing event type.', event);
    return res.status(400).send('Invalid webhook payload');
  }

  const eventType = event.type;
  const eventData = event.data; // Assuming event data is nested under 'data' key

  console.log(`Received webhook event: ${eventType}`);

  const handler = eventHandlers[eventType] || handleDefaultEvent;

  try {
    handler(eventData, eventType); // Pass eventType for default handler
    res.status(200).send('Webhook received and processed');
  } catch (error) {
    console.error(`Error processing webhook event ${eventType}:`, error);
    res.status(500).send('Error processing webhook');
  }
});

app.listen(PORT, () => {
  console.log(`Webhook receiver running on port ${PORT}`);
});
How it works: This Node.js Express snippet illustrates how to process and route incoming webhook events. It sets up an endpoint (`/webhook-receiver`) that listens for POST requests containing webhook payloads. Upon receiving an event, it extracts the `event.type` and `event.data` (assuming a common webhook structure) and then uses a predefined `eventHandlers` map to route the event to the correct handler function (e.g., `handleUserCreated`, `handleOrderPaid`). This pattern provides a structured way to manage various event types from external services and execute specific business logic for each.

Need help integrating this into your project?

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

Hire DigitalCodeLabs