JAVASCRIPT
Creating a Simple Webhook Listener Endpoint in Node.js Express
Set up a basic Node.js Express server to act as a webhook listener, capable of receiving and processing POST requests from external services.
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors'); // Required if your frontend is on a different origin
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors()); // Enable CORS for all routes (adjust as needed for security)
app.use(bodyParser.json()); // To parse JSON bodies
app.use(bodyParser.urlencoded({ extended: true })); // To parse URL-encoded bodies
// Webhook endpoint
app.post('/webhook/data', (req, res) => {
console.log('Webhook received data!');
console.log('Headers:', req.headers);
console.log('Body:', req.body);
// Example: Process the incoming data
if (req.body && req.body.event === 'order.created') {
console.log(`New order created: ${req.body.orderId} for customer ${req.body.customerEmail}`);
// Here you would typically save to a database,
// trigger other services, send notifications, etc.
} else if (req.body) {
console.log('Received generic webhook event:', req.body.event || 'unknown event');
} else {
console.log('Received webhook with no body.');
}
// Respond to the webhook sender to acknowledge receipt
// A 200 OK status indicates successful receipt and processing.
res.status(200).send('Webhook received successfully!');
});
// Optional: A simple GET route for health check or testing
app.get('/', (req, res) => {
res.status(200).send('Webhook listener is running!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Webhook listener server running on http://localhost:${PORT}`);
console.log('Listen for POST requests at /webhook/data');
});
// How to test (e.g., using curl):
// curl -X POST -H "Content-Type: application/json" \
// -d '{"event": "order.created", "orderId": "12345", "customerEmail": "[email protected]", "items": [{"id": 1, "name": "itemA"}]}' \
// http://localhost:3000/webhook/data
How it works: This Node.js Express snippet sets up a simple server to act as a webhook listener. It configures a POST endpoint (`/webhook/data`) that external services can send data to. The server uses `body-parser` to parse incoming JSON or URL-encoded payloads and logs the received data. This pattern is essential for integrating with services that send real-time updates (e.g., payment gateways, CRM systems, or CI/CD pipelines) rather than requiring constant polling. The listener processes the data and sends a 200 OK response to acknowledge successful receipt, which is a standard practice for webhook handlers.