Skip to content

Webhooks: sending and receiving

Working knowledgeConcept

A payment provider has to tell your shop that a card payment went through. It sends an HTTP request to a URL you gave it. That URL is public, so anyone can call it, and the real sender will sometimes call it twice. Here is how both sides make that safe.

01 Don’t poll, get called

Without webhooks, your shop asks the provider “has pay_7 settled yet?” every minute, for every open payment. Most answers are “no”. A webhook turns that around: the provider sends one POST to your URL when something happens.

PollingAsk until yesMany wasted requests, and news is up to one interval late.
WebhookTold once, at onceOne request per event. In return, you must run a public endpoint and handle repeats.

The sender is the one with news: a payment provider, a code host, a chat app. Your receiver is just an HTTP route. The hard part is that your route cannot tell a real call from a fake one, or a first call from a repeat, unless the request carries proof.

02 What a webhook request carries

This tutorial uses a simple scheme close to what most providers do. Names differ: Stripe sends Stripe-Signature: t=…,v1=…, GitHub sends X-Hub-Signature-256: sha256=…. The ideas are the same.

HTTP
POST /webhooks HTTP/1.1
Host: shop.example
Content-Type: application/json
Webhook-Id: evt_1
Webhook-Timestamp: 1767269160
Webhook-Signature: v1=5c1e0f… (example)
{"type":"payment.succeeded","payment":"pay_7"}
What each part is for
PartLets the receiver
Webhook-IdSpot a delivery it has already handled
Webhook-TimestampRefuse requests signed long ago
Webhook-SignatureCheck that the sender made exactly these bytes
BodyLearn what happened; often just ids, to fetch the details

The signature is an HMAC-SHA256 of id.timestamp.body, made with a secret that only the sender and you know. The provider shows it once when you register the URL.

03 Sending: queue, sign, retry

A sender that just calls fetch from its payment code loses events whenever the receiver is down. Real senders put each event on a queue and let workers deliver it, retrying until they get a 2xx.

One event, three delivery attempts
Step 1 of 7
Sender’s delivery queue
Empty
Delivery attempts (example times)
Empty
  • just happened
  • being sent
  • delivered
  • attempt failed

A customer’s card payment pay_7 succeeds at the payment provider. Your shop has asked to be told. Nothing is queued yet.

The last line matters most. A timeout tells the sender nothing about what your code did, so retries are designed in. Every sender that retries delivers at least once, which means sometimes more than once.

04 Receiving: verify, check the time, dedupe

The receiver runs three checks in order. Each one stops a different problem.

Three requests carrying one event
Step 1 of 11
Requests arriving (example times)
Empty
Receiver’s checks
Empty
Event ids already handled
Empty
  • just arrived or decided
  • passes, but isn’t enough
  • what settles it
  • rejected

Your receiver holds the shared secret and an empty store of handled event ids. It accepts signatures up to 5 minutes old.

SignatureStops forgeriesWithout the secret, nobody can make a request that verifies.
TimestampStops old replaysA captured request is only usable for the few minutes of the window.
Event idStops double workThe sender’s own retries carry fresh timestamps, so only the id catches them.

Keep handled ids for at least as long as the sender keeps retrying, which for many providers is days. A database table with a unique key on the id does the job and survives restarts.

05 A receiver in plain Node

This receiver uses only Node’s built-in modules. It reads the raw body, rejects stale or unsigned requests, and ignores ids it has handled.

webhook.js
const http = require('node:http');
const crypto = require('node:crypto');
const SECRET = process.env.WEBHOOK_SECRET;
const TOLERANCE_S = 300; // reject anything signed more than 5 minutes ago
const seen = new Set(); // in real life: a table with a unique key on the id
const queueForWorker = (event) => console.log('queued', event.type);
function problemWith(headers, raw) {
const id = headers['webhook-id'];
const ts = Number(headers['webhook-timestamp']);
const sig = String(headers['webhook-signature'] ?? '').replace(/^v1=/, '');
if (!id || !ts || !sig) return 'missing headers';
if (Math.abs(Date.now() / 1000 - ts) > TOLERANCE_S) return 'too old';
const expected = crypto
.createHmac('sha256', SECRET)

To test it, sign requests the way a sender would. This script uses openssl and curl.

send.sh
# usage: sh send.sh <event id> <unix time> <body>
SIG=$(printf '%s' "$1.$2.$3" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | sed 's/^.* //')
curl -s localhost:3000/webhooks \
-H "Webhook-Id: $1" -H "Webhook-Timestamp: $2" \
-H "Webhook-Signature: v1=$SIG" -d "$3"
Text
$ export WEBHOOK_SECRET=whsec_demo_only
$ node webhook.js &
$ BODY='{"type":"payment.succeeded","payment":"pay_7"}'
$ NOW=$(date +%s)
$ sh send.sh evt_1 $NOW "$BODY"
ok
$ sh send.sh evt_1 $NOW "$BODY"
duplicate, ignored
$ sh send.sh evt_2 $((NOW - 3600)) "$BODY"
too old

That is a real run with Node 24 and OpenSSL 3. Change one character of the body after signing and the answer is bad signature. The Set is only for the demo: it forgets everything on restart.

Verify the raw bytes you received, before any JSON parsing. A framework that parses the body and you then re-serialise it may reorder keys or change spacing, and the HMAC will never match. In Express, use express.raw() on the webhook route.

06 Answer fast, work later

Senders wait only briefly; GitHub, for example, treats a delivery as failed if you take more than 10 seconds. If your handler sends emails or calls other services before answering, slow days turn into timeouts, and timeouts into retries of work that already ran.

Work, then answer
app.post('/webhooks', async (req, res) => {
verify(req);
await fulfilOrder(req.body); // seconds
await sendReceiptEmail(req.body);
res.sendStatus(200);
});
Answer, then work
app.post('/webhooks', async (req, res) => {
verify(req);
await saveEventOnce(req.body); // insert, unique id
res.sendStatus(200);
// a background worker fulfils the order
});

Events can also arrive out of order: a retry of an older event may land after a newer one. Treat the event as a hint and read the current state from the sender’s API, or compare timestamps before you apply it.

07 When it bites

JSON.stringify(req.body)Signing the parsed bodyThe re-serialised JSON is not the bytes the sender signed. Keep the raw body for the check.
sig === expectedA plain string compareIt can return as soon as one character differs, which leaks timing. Use crypto.timingSafeEqual or hmac.compare_digest.
HMAC(body) onlyNo timestamp in the signatureA captured request stays valid forever. Sign the time with the body and enforce a window of a few minutes.
500 on unknown typeFailing on events you don’t useThe sender retries them for days. Answer 200 to event types you ignore.
url = customer inputSending to any URL (sender side)A customer can register http://169.254.169.254/ or an internal host. Resolve the address and refuse private ranges before each delivery.

08 Check yourself

Question

Your receiver got evt_9, did the work, but crashed before answering. What will the sender most likely do?

Question

An attacker replays a captured, correctly signed request one hour later. Which check stops it?

Question

Why should a receiver answer 200 to a duplicate instead of 409 Conflict?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?