Receiving and Verifying Webhooks
How to verify a webhook's HMAC signature, respond fast, and process the sender's retries without double-charging or double-emailing anyone.
Receiving and Verifying Webhooks
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A webhook URL is a public endpoint, so anyone who finds it can POST a forged payload to it — signature verification is what proves a request actually came from the sender you expect, not an attacker who guessed the path.
- The signature has to be checked against the raw request body, before any JSON parsing happens, because re-serializing a parsed object can change whitespace or key order and silently break a signature that was actually valid.
- A webhook handler should do almost nothing synchronously — verify the signature, hand the payload to a background job, and return 200 immediately, because the sender is waiting on that response and will retry you if it's slow.
- Because senders retry on anything but a fast 2xx, your handler will receive the same event more than once in normal operation, so the actual processing needs to be idempotent, not just retried.
Your webhook URL is a public door
The moment you expose an endpoint like POST /webhooks/stripe, you’ve published a door that anyone on the internet can knock on, not just Stripe. Nothing about the URL itself proves who’s sending the request — a bot that finds the path, or someone reading it out of a leaked log, can POST whatever payload it wants and your server has no way to tell the difference from the real thing, unless you build one in. That’s the entire problem this lesson solves: how do you know a webhook request actually came from the provider you think it did?
The fix providers converged on is HMAC signature verification. When you set up a webhook, the provider gives you a shared secret, known only to you and them. Every time they send you an event, they compute a hash of the payload using that secret — an HMAC (hash-based message authentication code) — and attach it as a header, something like Stripe-Signature or X-Hub-Signature-256. On your end, you take the same raw payload, recompute the HMAC with the same secret, and compare it to the header. If they match, only someone holding the secret could have produced that signature, and nobody but you and the provider holds it. If they don’t match, you reject the request — a forged payload from someone who doesn’t know the secret will never produce the right hash.
The gotcha: verify the raw bytes, not the parsed object
This is where a correct implementation trips people up. Most web frameworks parse the incoming JSON body into an object before your route handler even runs, as a convenience. But the signature was computed over the exact raw bytes the sender transmitted — specific spacing, specific key order, specific encoding. If you parse that body into an object and then try to re-serialize it to check the signature, you’ll often get a byte string that’s logically identical but not byte-identical, and the signature check fails even though the request was legitimate.
The fix is to capture the raw body — most frameworks let you register a raw-body parser just for the webhook route, before any JSON middleware runs — and verify against that untouched byte string. Only after verification succeeds do you parse it into something your code can work with. Get the order backwards and you’ll either reject valid webhooks (annoying, and a classic source of “why do half our webhooks fail in prod but work locally” bugs) or, worse, build a verification path that silently never actually checks anything.
A second detail worth building in from day one: many providers include a timestamp in the signed payload, specifically so you can reject requests that are suspiciously old — a captured, valid signature replayed hours later should still fail, even though the hash itself checks out. Checking “is this timestamp recent” alongside the HMAC comparison closes that gap.
Respond fast, do the work later
Once you’ve verified a request, resist the urge to process it right there in the handler. Providers enforce a response deadline — if your endpoint doesn’t return a 2xx within a few seconds, they treat the delivery as failed and retry it, often on an increasing backoff schedule, sometimes for days. If your handler is doing real work synchronously — writing to your database, calling another API, sending a notification — and that work is even a little slow, you’re racing a timer you don’t control.
The pattern that works: verify the signature, push the event onto a queue, return 200 immediately. The actual processing happens in a background job, on your own schedule, with your own retry logic if something downstream fails. This decouples “did we durably receive this event” (fast, synchronous, almost never fails) from “did we finish acting on it” (potentially slow, allowed to fail and retry on your terms instead of the sender’s).
Retries happen — design for duplicates
Here’s the part that catches people even after they’ve nailed verification and fast responses: webhook senders retry on anything short of a clean 2xx, and sometimes even on things that look clean to them but weren’t (a response that arrived a half-second after their timeout, for instance). In normal operation, not just failure scenarios, you will receive the same event more than once.
Every event carries a stable ID that’s identical across retries of the same delivery — an event.id from Stripe, a X-GitHub-Delivery header from GitHub. Idempotent handling means recording which IDs you’ve already processed — a unique constraint on a processed_webhook_events table is the simplest version — and checking before you act. See an ID you’ve handled before, acknowledge and skip. This is the same idempotency discipline a background job needs generally, applied specifically to the fact that the trigger itself is going to repeat.
Where this stops
Everything here assumes you’ve already decided webhooks are the right tool for getting notified about something. That decision — webhooks versus polling an API on a schedule — is a separate, earlier question, covered in Webhooks vs. Polling. This lesson picks up once you’ve made that call: given that you’re receiving webhooks, how do you receive them correctly.
Check yourself
Why isn't checking the sender's IP address or a secret in the URL enough to trust a webhook?
An IP allowlist can be bypassed by anything that can route through an allowed address, and a secret in the URL path tends to leak into logs, browser history, and proxies. HMAC signature verification proves the payload itself — the exact bytes received — was produced by someone holding the shared secret, independent of where the request came from.
Why does signature verification have to happen before the request body is parsed into an object?
The signature is computed over the exact raw bytes the sender sent. Parsing to JSON and later re-serializing it (even just to log it) can reorder keys or change whitespace, producing a byte string that no longer matches the signature — so the verification step has to read the untouched raw body, before any middleware touches it.
Why should a webhook handler respond before it's actually finished processing the event?
Most providers enforce a response timeout (Stripe's is a few seconds) and treat a slow or missing response as a delivery failure, which triggers a retry. If your handler does slow work — calling your own database, hitting another API — before responding, you risk the sender retrying a request that actually succeeded, creating duplicate deliveries for no reason. Verify, enqueue a background job, and return 200 right away.
If a sender retries the same event three times, what stops that from processing three times?
Every webhook event carries a stable identifier — an event ID, a delivery ID — that doesn't change between retries of the same event. Idempotent processing means checking that ID against what you've already handled (for example, a unique constraint on a processed_events table) before acting, so a duplicate delivery is recognized and skipped rather than reprocessed.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.