NODE.JS
Building a Basic Webhook Receiver with Node.js and Express
Set up a simple Node.js Express server to receive and process incoming webhook payloads for real-time data updates from external services and integrations.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 3000;
// Use body-parser middleware to parse JSON request bodies
// Some webhook providers might send different content types, e.g., 'text/plain'
// For JSON webhooks:
app.use(bodyParser.json());
// For raw body access (e.g., for signature verification, uncomment below and remove above line)
// app.use(bodyParser.raw({ type: 'application/json' }));
app.post('/webhook', (req, res) => {
console.log('--- Webhook Received ---');
// The payload will be in req.body if using bodyParser.json()
// If using bodyParser.raw(), req.body would be a Buffer.
console.log('Payload:', req.body);
// For production, you'd typically:
// 1. Verify webhook signature (if provided by the service).
// 2. Validate the payload structure.
// 3. Process the event (e.g., update database, trigger other services).
// 4. Respond quickly to avoid webhook provider timeouts.
// Example of processing based on an 'event_type'
if (req.body && req.body.event_type === 'user.created') {
console.log(`New user created: ${req.body.user_id}`);
// ... perform specific action ...
} else if (req.body && req.body.event_type === 'order.updated') {
console.log(`Order updated: ${req.body.order_id}`);
// ... perform specific action ...
}
// Acknowledge receipt to the webhook sender
res.status(200).send('Webhook received successfully!');
});
// Basic health check endpoint
app.get('/', (req, res) => {
res.status(200).send('Webhook receiver is running.');
});
app.listen(PORT, () => {
console.log(`Webhook receiver listening on port ${PORT}`);
});
How it works: This Node.js Express snippet sets up a basic server to act as a webhook receiver. It uses `body-parser` middleware to automatically parse incoming JSON payloads. When a POST request is made to the `/webhook` endpoint, it logs the received payload and can include logic to process different event types. It's crucial for real-time data synchronization between different services, providing an endpoint for external APIs to push data updates.