Setting Up Webhooks in Node.js: Best Practices and Examples
Webhooks allow your app to receive real-time data from third-party services. This guide covers how to securely set up and verify webhooks in Node.js.
1. Create a Webhook Endpoint
Set up an Express route to receive POST requests from your webhook provider.
app.post('/webhook', express.json(), (req, res) => {
const event = req.body;
// Process webhook event here
console.log('Received webhook event:', event);
res.status(200).send('OK');
});
2. Verify Webhook Signature
To prevent spoofing, verify the webhook payload using a shared secret.
const crypto = require('crypto');
function verifySignature(req, res, next) {
const signature = req.headers['x-webhook-signature'];
const payload = JSON.stringify(req.body);
const expectedSignature = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(payload)
.digest('hex');
if (signature !== expectedSignature) {
return res.status(401).json({ error: 'Invalid signature' });
}
next();
}
3. Apply Verification Middleware
Use the verification middleware on your webhook route.
app.post('/webhook', express.json(), verifySignature, (req, res) => {
const event = req.body;
// Process verified webhook event
res.status(200).send('Webhook received');
});
4. Handle Common Webhook Pitfalls
- Replay Attacks: Use a timestamp or nonce in payloads and reject duplicates.
- Idempotency: Make webhook handlers idempotent to avoid duplicate processing.
- Timeouts: Respond quickly to webhook requests; defer heavy processing to background jobs.
Final Advice
Webhooks are powerful but must be treated with care. Always verify signatures, handle retries gracefully, and log received events for debugging.
