A webhook is an automated message sent from one application to another when a specific event occurs. Instead of constantly asking "did anything happen?" (polling), webhooks push notifications instantly when events occur.
Webhooks vs. Polling
Polling (The Old Way)
Your app repeatedly asks: "Any new orders?" every few seconds.
- Wastes resources
- Delayed updates
- Constant requests even when nothing changes
Webhooks (The Better Way)
E-commerce platform tells your app: "New order just came in!"
- Real-time updates
- No wasted requests
- Only fires when events occur
How Webhooks Work
- You register a webhook URL with a service
- You specify which events you care about
- When an event happens, the service POSTs data to your URL
- Your server processes the data
Common Webhook Examples
Payment Processing (Stripe)
POST /webhooks/stripe
{
"type": "payment_intent.succeeded",
"data": {
"amount": 2000,
"customer": "cus_123"
}
}
Form Submissions
Contact form submitted → Webhook → CRM updated
E-commerce
New order → Webhook → Inventory system updated
CI/CD
Code pushed → Webhook → Build triggered
Chat Notifications
Server alert → Webhook → Slack message
Setting Up Webhooks
1. Create an Endpoint
app.post('/webhooks/stripe', (req, res) => {
const event = req.body;
switch (event.type) {
case 'payment_intent.succeeded':
handlePaymentSuccess(event.data);
break;
// Handle other events
}
res.status(200).send('OK');
});
2. Register with Service
In Stripe dashboard (for example):
- Endpoint URL: https://yoursite.com/webhooks/stripe
- Events: payment_intent.succeeded, payment_intent.failed
3. Verify Signatures
Always verify webhooks are from the real source:
const sig = req.headers['stripe-signature'];
const event = stripe.webhooks.constructEvent(req.body, sig, secret);
Webhook Best Practices
Security
- Verify webhook signatures
- Use HTTPS
- Validate payload structure
- Implement IP whitelisting if possible
Reliability
- Respond quickly (process asynchronously)
- Return 200 status for successful receipt
- Handle retries (webhooks may be sent multiple times)
- Implement idempotency (handle duplicates gracefully)
Monitoring
- Log all webhook events
- Alert on failures
- Monitor delivery latency
Webhook Challenges
- Ensuring your endpoint is always available
- Handling out-of-order delivery
- Managing failed deliveries
- Dealing with sensitive data in payloads