What Are Webhooks? Complete Guide for Developers
Webhooks are one of the most powerful tools for building real-time integrations. This guide explains what webhooks are, how they work, when to use them, and how to implement them securely.
What Is a Webhook?
A webhook (sometimes called a "reverse API" or "HTTP callback") is an automated message sent from one application to another when a specific event occurs. Unlike traditional APIs where your application requests data, webhooks push data to your application automatically.
Think of webhooks like notification alerts on your phone. Instead of opening every app to check for updates (polling), apps send you push notifications when something important happens. Webhooks work the same way for applications.
Real-World Example:
When a customer completes a payment on Stripe, Stripe immediately sends a webhook to your server with the payment details. Your application receives this notification instantly and can fulfill the order, send a confirmation email, or update your database—all without constantly checking Stripe's API for new payments.
How Do Webhooks Work?
Webhooks follow a simple request-response pattern:
Register Your Webhook Endpoint
You provide the service with a URL (webhook endpoint) where they should send event notifications. This is typically a POST endpoint on your server like https://yourdomain.com/webhooks/stripe.
Event Occurs
Something happens in the external service that triggers a webhook—a payment succeeds, a file is uploaded, code is pushed to a repository, a form is submitted, etc.
Service Sends HTTP POST Request
The service makes an HTTP POST request to your webhook URL, including event data in the request body (usually JSON). This happens automatically and immediately when the event occurs.
Your Server Processes the Event
Your webhook endpoint receives the request, validates it (important!), processes the event data, and responds with a 200 OK status to confirm receipt.
Example webhook payload from Stripe:
{
"id": "evt_1MqLv5LkdIwHu7ix5JqXsN3E",
"type": "payment_intent.succeeded",
"data": {
"object": {
"id": "pi_3MqLv5LkdIwHu7ix5u8K2nEb",
"amount": 4999,
"currency": "usd",
"status": "succeeded",
"customer": "cus_NffrFeUfNV2Hib"
}
}
}Webhooks vs REST APIs: What's the Difference?
| Aspect | REST API (Pull) | Webhook (Push) |
|---|---|---|
| Data Flow | You request data | Service sends data to you |
| Timing | On-demand (when you ask) | Real-time (when event happens) |
| Efficiency | Requires polling (wasteful) | Event-driven (efficient) |
| Latency | Depends on polling interval | Near-instant delivery |
| Setup Complexity | Simple (make HTTP request) | Moderate (need public endpoint) |
| Best For | On-demand data retrieval | Real-time event notifications |
When to use webhooks: Real-time notifications (payment updates, order status changes), event-driven workflows (CI/CD pipelines, automated testing), and integrations where polling would be inefficient (monitoring thousands of repositories for new commits).
When to use REST APIs: Fetching data on-demand (displaying user profile), searching/filtering (finding products), and bulk operations (exporting data).
Common Webhook Use Cases
💳 Payment Processing
Stripe, PayPal, and Square send webhooks when payments succeed, fail, are refunded, or when subscriptions are created/cancelled. This lets you fulfill orders immediately without polling payment status.
🔔 Monitoring & Alerts
Services like API Status Check, Datadog, and PagerDuty send webhooks when servers go down, performance thresholds are breached, or errors spike—enabling instant incident response.
🚀 CI/CD Pipelines
GitHub, GitLab, and Bitbucket send webhooks on git push events, triggering automated builds, tests, and deployments. This powers modern DevOps workflows.
💬 Chat & Messaging
Slack, Discord, and Teams use webhooks for bot commands, slash commands, and message events. When someone types /deploy, a webhook triggers your deployment script.
📋 Form Submissions
Typeform, Google Forms (via Zapier), and Tally send webhooks when forms are submitted, letting you process responses, send confirmation emails, or add leads to your CRM instantly.
📦 E-commerce & Shipping
Shopify sends webhooks for new orders, order cancellations, and inventory changes. Shipping providers like ShipStation notify when packages are shipped, in transit, or delivered.
How to Implement a Webhook Endpoint
Here's a simple Node.js/Express example showing the essential elements of a webhook handler:
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.json());
app.post('/webhooks/stripe', async (req, res) => {
const signature = req.headers['stripe-signature'];
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
// 1. Verify webhook signature (CRITICAL for security)
try {
const event = stripe.webhooks.constructEvent(
req.body,
signature,
webhookSecret
);
} catch (err) {
console.error('⚠️ Webhook signature verification failed:', err.message);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// 2. Handle the event
switch (event.type) {
case 'payment_intent.succeeded':
const payment = event.data.object;
console.log(`💰 Payment ${payment.id} succeeded`);
await fulfillOrder(payment);
break;
case 'payment_intent.failed':
console.log('❌ Payment failed:', event.data.object.id);
await notifyCustomer(event.data.object);
break;
default:
console.log(`Unhandled event type: ${event.type}`);
}
// 3. Return 200 immediately (don't make service wait)
res.status(200).json({ received: true });
});
app.listen(3000, () => console.log('Webhook server running on port 3000'));⚠️ Critical Implementation Rules:
- Always verify signatures — Never trust webhook data without validation
- Respond quickly — Return 200 within 5-10 seconds; process async if needed
- Handle idempotency — Services may send the same event multiple times
- Use HTTPS only — Never accept webhooks over plain HTTP
- Log everything — Keep audit trail of all received webhooks
Monitor Your Webhook Endpoints
Get instant alerts when your webhook endpoints go down or respond slowly. Real-time monitoring from multiple locations.
Try Better Stack Free →Webhook Security Best Practices
1. Verify Webhook Signatures (HMAC)
Most services sign webhook payloads with HMAC-SHA256. Always validate this signature before processing the payload. Without signature verification, anyone could send fake webhooks to your endpoint.
2. Use HTTPS Endpoints Only
Never configure webhook URLs with http://. Webhook payloads often contain sensitive data (payment info, user details). Always use SSL/TLS encryption.
3. Implement Idempotency
Services may send the same webhook multiple times (network retries, failovers). Use event IDs to deduplicate: store processed event IDs in a database and skip already-processed events.
4. Rate Limit Webhook Endpoints
Protect against abuse by rate-limiting webhook endpoints. Even with signature verification, malicious actors could spam your endpoint with valid-looking but replayed old webhooks.
5. Validate IP Allowlists (Where Available)
Some services (like GitHub, Twilio) publish webhook IP ranges. If available, configure your firewall to only accept webhooks from these IPs as an additional security layer.
Webhook Reliability & Error Handling
What Happens If Your Endpoint Is Down?
Most webhook providers implement retry logic with exponential backoff:
- Immediate delivery attempt
- Retry after 1 minute (if failed)
- Retry after 5 minutes
- Retry after 30 minutes
- Retry after 2 hours
- Retry after 6 hours
- Final retry after 24 hours
After exhausting retries (typically 24-72 hours), the service gives up. Check your provider's documentation for their specific retry policy.
Monitoring Webhook Health
Critical webhook endpoints deserve monitoring just like your main API. Set up alerts for:
- Webhook delivery failures — Check provider logs/dashboards daily
- Signature validation failures — Could indicate attack attempts or misconfiguration
- Processing errors — Your code throwing exceptions while handling webhooks
- Latency spikes — Slow responses may cause provider retries
💡 Pro Tip: Fallback Strategy
For mission-critical integrations, don't rely solely on webhooks. Implement a hybrid approach: use webhooks for real-time updates, but also run periodic polling (every 15-30 minutes) as a backup to catch any missed events. Services like Stripe provide API endpoints to list recent events.
Testing Webhooks During Development
Webhooks require a publicly accessible URL, which creates challenges for local development. Here are common solutions:
1. ngrok (Most Popular)
Creates a secure tunnel from a public URL to your localhost. Perfect for testing:
# → https://abc123.ngrok.io forwards to localhost:3000
2. Webhook Testing Tools
Services like webhook.site, RequestBin, and Svix Play let you inspect webhook payloads without writing code—great for understanding event structure before implementing handlers.
3. Provider Test Events
Most services (Stripe, GitHub, Shopify) let you send test webhooks from their dashboard. Use these to verify your endpoint works before going live.
Frequently Asked Questions
Can webhooks send data back to the source?
Not directly. Webhooks are one-way: the service sends data to you, you acknowledge receipt with a 200 response. If you need to send data back, make a separate API call to the service (not in the webhook response body—that's ignored).
Are webhooks better than polling?
For real-time events, yes. Polling wastes resources (most requests return "no new data") and has latency (you only check every N seconds). Webhooks deliver events instantly with zero wasted requests. However, polling is simpler to implement and doesn't require public endpoints.
What's the difference between webhooks and WebSockets?
WebSockets maintain a persistent two-way connection (like a phone call). Webhooks are one-off HTTP requests (like text messages). Use WebSockets for continuous real-time data (chat, live updates). Use webhooks for discrete events (payment succeeded, file uploaded).
How do I debug failed webhook deliveries?
Check your provider's webhook dashboard—most show delivery logs with request/response details. Common issues: signature validation failures (wrong secret), timeout (your endpoint too slow), SSL certificate errors (invalid HTTPS cert), and firewall blocks (endpoint not publicly accessible).
Never Miss a Webhook Delivery
Monitor uptime, track response times, and get alerted instantly when services your webhooks depend on go down.
Try Better Stack Free →Conclusion: Webhooks Power Modern Integrations
Webhooks are the backbone of real-time integrations. They eliminate inefficient polling, reduce latency, and enable event-driven architectures. Whether you're building payment flows, CI/CD pipelines, monitoring systems, or chat integrations, understanding webhooks is essential for modern software development.
The key to successful webhook implementation is security-first thinking: always verify signatures, use HTTPS, handle retries gracefully, and monitor delivery health. Follow these practices and you'll build reliable, efficient real-time integrations.
Monitor Your APIs & Webhooks
API Status Check helps you monitor API uptime, track webhook delivery health, and get instant alerts when services go down. Free for developers.