JAVASCRIPT

Set Up a Basic Webhook Receiver in Node.js Express

Create a simple Node.js Express endpoint to receive and process incoming webhook payloads, essential for event-driven API integrations and reacting to external events.

const express = require('express');
const bodyParser = require('body-parser'); // For parsing JSON or URL-encoded bodies

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

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

// Webhook endpoint
app.post('/webhook', (req, res) => {
  const event = req.body; // The payload sent by the webhook provider

  if (!event) {
    return res.status(400).send('Request body is empty');
  }

  console.log('Received webhook event:', event);

  // --- Your custom logic here ---
  // Example: Process the event based on its type
  if (event.type === 'order.created') {
    console.log(`New order created: ${event.data.orderId}`);
    // Call another service, update database, send notification, etc.
  } else if (event.type === 'user.updated') {
    console.log(`User updated: ${event.data.userId}`);
  }
  // -------------------------------

  // Respond to the webhook sender to acknowledge receipt
  // A 200 OK status code tells the sender the webhook was received successfully.
  res.status(200).send('Webhook received successfully!');
});

// Basic route for health check or root access
app.get('/', (req, res) => {
  res.send('Webhook listener is running!');
});

app.listen(PORT, () => {
  console.log(`Webhook server listening on port ${PORT}`);
  console.log(`Endpoint: http://localhost:${PORT}/webhook`);
});

// Note: For production, consider adding webhook signature verification
// to ensure the request truly comes from the expected source. This snippet
// focuses on basic reception and parsing only.
How it works: This Node.js Express snippet sets up a basic HTTP POST endpoint designed to receive webhook payloads. It uses `body-parser` to automatically parse JSON data sent by the webhook provider. Upon receiving an event, it logs the payload and includes a placeholder for custom logic to process different event types. Responding with a 200 OK status code is crucial to acknowledge successful receipt to the webhook sender, preventing repeated deliveries. Remember that for production, adding webhook signature verification is highly recommended for security, though not included here.

Need help integrating this into your project?

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

Hire DigitalCodeLabs