JAVASCRIPT
Create a Simple Webhook Receiver in Node.js with Express
Build a basic webhook endpoint using Express.js to receive and process real-time data from external services, perfect for event-driven architectures.
// 1. Install Express: npm install express body-parser
// 2. In your Node.js file (e.g., server.js):
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());
// Simple webhook endpoint
app.post('/webhook', (req, res) => {
console.log('--- Webhook Received ---');
console.log('Headers:', req.headers);
console.log('Body:', req.body);
// --- IMPORTANT ---
// In a real application, you would add validation here:
// 1. Verify the sender (e.g., check 'x-hub-signature' or IP whitelist)
// 2. Validate the payload schema
// 3. Process the event asynchronously (e.g., queue it for a background job)
// Respond quickly to acknowledge receipt
res.status(200).send('Webhook received successfully!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Webhook receiver listening on port ${PORT}`);
console.log(`Send POST requests to http://localhost:${PORT}/webhook`);
});
// Example of how to test (e.g., using curl):
// curl -X POST -H "Content-Type: application/json" \
// -d '{"event": "order.created", "data": {"orderId": "123", "total": 99.99}}' \
// http://localhost:3000/webhook
How it works: This Node.js snippet, using the Express.js framework, demonstrates how to create a simple webhook receiving endpoint. Webhooks allow external services to push real-time data to your application when certain events occur. The `app.post('/webhook', ...)` route listens for incoming POST requests to the `/webhook` path. `body-parser` is used to parse the JSON payload from the request body. The received data (headers and body) is logged, and a `200 OK` status is immediately sent back to acknowledge receipt. Critical security and processing steps, like sender verification and asynchronous processing, are highlighted as necessary additions for production use.