JAVASCRIPT
Simple Webhook Sender and Receiver with Node.js
Set up a basic Node.js Express server to receive incoming webhooks and a client-side snippet to send a simple webhook payload, demonstrating the fundamental mechanism of webhook communication.
// --- Webhook Receiver (Node.js with Express) ---
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json()); // Middleware to parse JSON request bodies
app.post('/webhook-endpoint', (req, res) => {
console.log('--- Webhook Received ---');
console.log('Headers:', req.headers);
console.log('Body:', req.body);
// In a real application, you would process the webhook payload here.
// e.g., update a database, send an email, trigger another process.
if (req.body && req.body.eventType === 'user.created') {
console.log(`New user created: ${req.body.data.username}`);
} else {
console.log('Unknown event type or malformed body.');
}
res.status(200).send('Webhook received successfully!');
});
app.listen(PORT, () => {
console.log(`Webhook receiver listening on http://localhost:${PORT}`);
console.log(`Send POST requests to http://localhost:${PORT}/webhook-endpoint`);
});
// --- Webhook Sender (JavaScript - can be client-side or server-side) ---
async function sendWebhook(url, payload) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// 'X-Custom-Signature': 'some-hashed-signature' // For production, add security like signature verification
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to send webhook: ${response.status} ${response.statusText} - ${errorText}`);
}
console.log('Webhook sent successfully!', await response.text());
} catch (error) {
console.error('Error sending webhook:', error);
}
}
// Example usage for sending a webhook:
// This would typically be triggered by an event in your application
const webhookPayload = {
eventType: 'user.created',
timestamp: new Date().toISOString(),
data: {
userId: 'abc-123',
username: 'john.doe',
email: '[email protected]'
}
};
// Call this function when an event occurs, e.g., after a user registers
// sendWebhook('http://localhost:3000/webhook-endpoint', webhookPayload);
How it works: This snippet provides a fundamental example of both a webhook sender and a receiver using Node.js. The receiver is an Express server configured to listen for POST requests at `/webhook-endpoint`, parsing the JSON body and logging its contents. The sender is a generic JavaScript function that uses `fetch` to send a JSON payload to a specified URL. This illustrates the basic 'fire-and-forget' communication pattern where one service notifies another about an event without waiting for a direct response, enabling asynchronous communication between different systems.