JAVASCRIPT

Building a Basic Node.js Webhook Receiver

Implement a straightforward Node.js Express server to receive and process incoming webhook payloads, enabling real-time event-driven integrations with external services.

const express = require('express');
const bodyParser = require('body-parser'); // To parse JSON payloads

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

// Use body-parser middleware to parse JSON request bodies
app.use(bodyParser.json());

// Basic middleware to log all incoming requests
app.use((req, res, next) => {
    console.log(`
[${new Date().toISOString()}] Incoming ${req.method} request to ${req.path}`);
    next();
});

/**
 * Webhook endpoint to receive data from an external service.
 * This example simply logs the received payload.
 * In a real application, you would process this data (e.g., save to DB, trigger an action).
 */
app.post('/webhook-listener', (req, res) => {
    console.log('Received Webhook Payload:');
    console.log(JSON.stringify(req.body, null, 2)); // Log the JSON payload nicely

    // Depending on the webhook provider, you might need to send specific status codes
    // Common practice is to return 200 OK to acknowledge receipt.
    res.status(200).send('Webhook received successfully!');
});

// Root endpoint for simple health check or info
app.get('/', (req, res) => {
    res.send('Webhook Listener is running. Send POST requests to /webhook-listener');
});

// Start the server
app.listen(PORT, () => {
    console.log(`Webhook listener running on http://localhost:${PORT}`);
    console.log(`Send POST requests to: http://localhost:${PORT}/webhook-listener`);
});
How it works: This Node.js Express snippet sets up a simple server to act as a webhook receiver. It uses `body-parser` to automatically parse incoming JSON payloads. The `/webhook-listener` endpoint is configured to accept POST requests, where it logs the received data. In a production environment, you would replace the logging with actual business logic, such as updating a database, triggering other services, or sending notifications, acknowledging receipt with a `200 OK` status.

Need help integrating this into your project?

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

Hire DigitalCodeLabs