15 min read
What is a webhook and how to make it secure
In one sentence: A webhook is a request another service makes to your server to tell you about something, like a payment. To trust it, you check its HMAC signature, and to avoid counting it twice, you write down its id. An Idempotency-Key does the same with the POST requests your clients repeat.
What you will learn
- Explain what a webhook is and what it gains over asking every minute (polling).
- Check a webhook's HMAC signature, on the body exactly as it arrives.
- Answer quickly and process each event only once, even if it arrives repeated.
- Make repeating a POST duplicate nothing, with the Idempotency-Key header.
Before you start, read: 06-serialization.md
The problem
Section titled “The problem”A customer pays for order 25 at the shop. Not in your API, but at the payment gateway: the company that takes card payments for the shop, like Stripe or PayPal. How does the shop find out it can now prepare the package?
It could ask every minute: with 50 pending orders, 72,000 questions a day, almost all of them to hear “not yet.” The usual way is the opposite: the gateway calls the shop when someone pays. But as soon as the shop opens an address for that, POST /v2/webhooks/payments, two questions come up:
- Who is calling? Anyone with
curlcan write “order 25 is paid” and walk away with a free hoodie. - How many times? If the shop’s response gets lost, the gateway sends the notification again: the same payment arrives twice.
You already know the second one: Luis’s repeated POST on the train, from the methods lesson of Phase 2. Today you solve it in both directions.
The analogy
Section titled “The analogy”The analogy
Luis makes things to order. Instead of calling the bank every hour to ask whether a customer has paid, he asks the bank to send him a letter when the money comes in.
So that nobody can pretend to be the bank, they agree on a secret word that is never written down. At the bottom of each letter, the bank puts a code calculated from that word and the text. Luis does the math again: if someone changed the amount, it doesn’t add up.
And each letter carries a reference number: if the post office delivers the same one twice, Luis doesn’t send another package.
Where the analogy breaks down
- Nobody calculates a code like that in their head; a computer does it in microseconds: that’s the HMAC.
- A letter rarely arrives twice. A webhook is repeated on purpose: whoever sends it keeps trying until they get a “received.”
- A letter takes days. A webhook arrives in less than a second, and whoever sends it only waits a few seconds.
How it really works
Section titled “How it really works”Asking every minute or being told
Section titled “Asking every minute or being told”This is what asking every so often looks like:
- The payment gateway → The shopnot yet
- The payment gateway → The shopnot yet
- The payment gatewaythe customer pays
- The payment gateway → The shopyes, paid
That’s PollingAsking a server every so often whether something has changed, even though the answer is almost always no. It’s the opposite of being notified, the way a webhook does it.Go to definition: it works, but it wastes requests and finds out late. A WebhookAn address on your server that another service sends a request to when something happens, such as a completed payment. Instead of you asking every so often whether something has changed, they let you know.Go to definition turns it around: the shop gives the gateway a URL of its own, and the gateway makes a POST to it when something happens.
- The shopmarks order 25 as paid
- The shop → The payment gateway200
The gateway is the ClientThe program that starts the conversation by asking another program, the server, for something. Your browser is a client.Go to definition, and the shop, the ServerA program that waits for requests and answers them. By extension, the computer it runs on is also called a server.Go to definition. There’s nothing new in HTTP: a POST with JSON, one per event, right when it happens.
The price: the shop needs a URL the gateway can reach from the internet, and a real one can’t reach your localhost. That’s why, here, the gateway is a fake program on your computer.
What it sends is called an event: something that happened, with a name and its own id. Its shape, in src/schemas.ts:
// The payment gateway's notification: what happened (type), with which order and an event id.export const paymentEventSchema = z .object({ id: z.string({ error: 'Must be text' }).min(1).openapi({ example: 'evt_1234' }), type: z.literal('payment.completed', { error: 'Only completed payments are accepted' }), orderId: z.number({ error: 'Must be a number' }).int().openapi({ example: 7 }), }) .openapi('PaymentEvent');
// What the shop answers: received, and whether it had already received it before.export const ackSchema = z .object({ received: z.string(), repeated: z.boolean() }) .openapi('Acknowledgement');idis the event’s id, not the order’s: it will be used to recognize repeated ones.z.literal('payment.completed')only accepts that exact text.ackSchemais what the shop answers.
The signature: an HMAC of the body with a secret
Section titled “The signature: an HMAC of the body with a secret”Anyone can reach that URL. Before believing a notification, the shop needs to know it comes from the gateway and that nobody changed it. Webhooks solve it with a SecretA piece of data that gives access to something and that only the people and programs that need it should know, like a database password or an API key. It’s never written inside the code.Go to definition only the two sides know. See what is done with it in the REPLREPL stands for Read-Eval-Print Loop.A way of working with a language in which you type a line of code, it runs and you see the result right away, without creating any file. In Node.js, you open it by typing node, with nothing else, in the terminal.Go to definition (type node in the terminal):
In the REPL: the same body, another body and another secret
const { createHmac } = await import('node:crypto')const secret = 'the-shop-and-gateway-secret'createHmac('sha256', secret).update('{"orderId":25}').digest('hex')createHmac('sha256', secret).update('{"orderId":26}').digest('hex')createHmac('sha256', 'another-secret').update('{"orderId":25}').digest('hex')createHmac('sha256', secret).update('{"orderId":25}').digest('hex')What you will see:
undefinedundefined'c8e8c2fb491c47848464cbf4bfae2e3130af28804f919f1ba12e4994235f4a2e''00fa80805b54783b8455349c5378b40db6ccb800dab420cd71f223a56465bc14''35a9d400d0eea560a810ba29bd738d384a761ace7cd12c679492be8fdd20792c''c8e8c2fb491c47848464cbf4bfae2e3130af28804f919f1ba12e4994235f4a2e'createHmac comes in node:crypto, Node’s cryptography ModuleA code file that offers some of its pieces to other files, which bring them in with import. This way a program is split across several files and can use the pieces that come with Node.js or with a package.Go to definition. Compare the four long lines:
- The first and the last are the same: the same body with the same secret always gives the same result, on your computer too.
- The second changes one character of the body,
26instead of25, and looks nothing like it. Neither does the third, with another secret.
The outputs in this lesson are from Node 26.
That’s an HMACHMAC stands for Hash-based Message Authentication Code.A signature computed with a hash from a message and a secret that both parties know. Whoever has the secret can check that the message comes from the other party and that nobody has changed it; whoever doesn’t have it can’t forge one.Go to definition: a HashA short, fixed-size summary calculated from some data, like a fingerprint. The same data always gives the same hash, and the smallest change gives a completely different one. Git calls each commit by its hash.Go to definition, like the ones in the Git lesson of Phase 1, calculated with the message and a secret together. Whoever has the secret can sign any body; whoever doesn’t, can’t, even if they know the formula and have seen a thousand signed notifications.
This is how it’s signed, in a new file, src/signature.ts, which the shop and the fake gateway will use:
// An HMAC-SHA256 of the body, exactly as it arrives, with a secret only the gateway and the shop// know. Without the secret it can't be calculated; if a single byte of the body changes, it all// changes.export function sign(body: string, secret: string): string { return `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`;}createHmac('sha256', secret)sets up the calculation with the SHA-256 formula;.update(body)gives it the text, and.digest('hex'), the result in hexadecimal: 64 characters.- It starts with
sha256=, the formula used. The signature travels in theX-SignatureHeaderInformation a protocol puts in front of its data to do its job. In HTTP they are text lines of the form “Name: value”, such as Host or Content-Type; in TCP or IP they are numbers in fixed positions, such as ports or addresses.Go to definition; GitHub signs the same way, inX-Hub-Signature-256.
Unlike the Digital signatureA few bytes someone computes from a message with their private key. With the public key, anyone can check that the message hasn’t changed and that the owner of that key signed it.Go to definition from Phase 0, here the same secret signs and checks. That’s why it lives only at the gateway and on your server, in the WEBHOOK_SECRET Environment variableA name with a value, like PORT=3000, that a program receives when it starts from whoever starts it, for example the shell. It lets you configure the program without changing its code and give it secrets without writing them in it.Go to definition, which src/config.ts requires at startup. A real gateway gives it to you when you register your URL (in Stripe it starts with whsec_).
Checking the signature: the body as it is, in constant time
Section titled “Checking the signature: the body as it is, in constant time”Checking is doing the math again and comparing, in the same file:
// It calculates the signature the request should carry and compares it with the one it carries.// timingSafeEqual takes the same time whether it matches or not: with ===, someone timing it could// guess it letter by letter.export function validSignature( body: string, signature: string | undefined, secret: string,): boolean { if (signature === undefined) return false; const expected = Buffer.from(sign(body, secret)); const received = Buffer.from(signature); // timingSafeEqual only compares two things of the same size. return expected.length === received.length && timingSafeEqual(expected, received);}signature: string | undefined: the header may be missing, and then it isn’t valid.Buffer.fromturns each text into bytes, theBufferfrom lesson 4 of Phase 3.timingSafeEqualtakes the same time whether it matches or not. With===, the comparison stops at the first different character: the more it gets right, the longer it takes. By timing thousands of attempts, someone could guess the signature character by character.- It only compares bytes of the same size: that’s why the lengths are checked first.
A new MiddlewareA function a server runs with the requests of the routes it’s registered on (all of them, or only some), before the code that answers them. It can answer the request itself or pass it on to the next one, and it sees the response on its way back. It’s used for what affects many requests, like writing them to the log, granting CORS permission or asking for a credential.Go to definition uses it, src/middleware/verify-signature.ts:
import type { MiddlewareHandler } from 'hono';import { config } from '../config.ts';import { problem, problemType } from '../problems.ts';import { validSignature } from '../signature.ts';
// It checks the signature before anything else: with the body as text, byte by byte as it came.// If it were read as JSON and written again, one extra space would change the signature. If it's// not valid, 400 and not 401: a 401 requires WWW-Authenticate, which says how to identify// yourself, and a signature has no such scheme.export const verifySignature: MiddlewareHandler = async (c, next) => { const body = await c.req.text(); if (!validSignature(body, c.req.header('X-Signature'), config.WEBHOOK_SECRET)) { return problem(c, { type: problemType('invalid-signature'), title: 'The signature is not valid', status: 400, detail: 'The X-Signature header does not match this body', }); } await next();};Look at c.req.text(): it reads the Body (of a request or response)The data an HTTP message carries after the blank line that ends the headers, such as the fields of a form, some JSON or an image. The Content-Type header says what format it’s in, and Content-Length how many bytes it takes up.Go to definition as text, exactly as it arrived. The signature is checked on the original body, never on the JSON read and written again. JSON.stringify rewrites it without the original’s spaces, and one extra character changes the signature.
If it doesn’t match, 400, with the shape from lesson 2, “Errors.” Not 401: a 401 promises a WWW-Authenticate header that says how to identify yourself (lesson 6 of Phase 3), and a signature has no scheme like that. Stripe’s example also answers 400.
The route, in src/contract.ts, puts the middleware in front, like adminOnly in lesson 5, “OpenAPI”:
// The webhook: the payment gateway calls here when an order is paid. verifySignature goes before// everything else: a notification without a valid signature isn't read.export const receivePayment = createRoute({ method: 'post', path: '/webhooks/payments', tags: ['Webhooks'], summary: 'The payment gateway reports a payment', middleware: [verifySignature] as const, request: { headers: z.object({ 'x-signature': z.string().openapi({ example: 'sha256=5f2b…' }) }), body: jsonBody(paymentEventSchema), }, responses: { 200: asJson(ackSchema, 'Received'), 400: withProblem('The signature is not valid'), 422: invalidData, },});middleware: [verifySignature] goes before ValidationChecking, every time it arrives, that the data the client sends is what was expected before using it: that no field is missing, that a number is a number and that it’s within what’s allowed. If something doesn’t match, the server answers with an error and stops there.Go to definition: without a good signature, 400, without checking whether the JSON matches the SchemaThe description of what some data must look like: which fields it has, whether each one is a number or text, and which values are accepted. A program compares the incoming data with it and says whether it matches or what’s wrong.Go to definition.
Answer quickly and leave the work for later
Section titled “Answer quickly and leave the work for later”Whoever sends a webhook doesn’t wait long. GitHub gives 10 seconds: without a 2xx in time, the notification has failed. Stripe retries it for up to three days. The code that answers, in src/v2.ts:
// By the time it gets here, the signature is already checked and the event matches its schema.// The response has to be quick: if the gateway doesn't get a 2xx in time, it retries. That's why,// if the work were long (an email, an invoice), it would be left for later (a queue, Phase 9).v2.openapi(contract.receivePayment, (c) => { const event = c.req.valid('json'); // The same event again: receipt is acknowledged and nothing else is done. if (processedEvents.has(event.id)) { return c.json({ received: event.id, repeated: true }, 200); } const order = findOrder(event.orderId); if (!order) { return invalidData(c, [{ field: 'orderId', problem: 'No such order' }]); } processedEvents.add(event.id); // Only a pending order becomes paid: a cancelled one stays cancelled. if (order.status === 'pending') order.status = 'paid'; return c.json({ received: event.id, repeated: false }, 200);});- If the order doesn’t exist,
422, like any data that isn’t valid. - If it’s pending, it becomes
paid. A cancelled one stays cancelled.
An email or an invoice would go to a queue, for later (Phase 9). First “received”; the work, afterwards.
Notifications repeat: process each event once
Section titled “Notifications repeat: process each event once”Payment gateways promise that each notification arrives at least once, not exactly once. It’s enough for your 200 to get lost:
- The shopmarks the order as paid
- The shop → The payment gateway200, which gets lost on the way
- The payment gatewayno response arrives: it retries
- The shopit already knows evt_7: it does nothing
- The shop → The payment gateway200, repeated
To recognize it, the shop writes down the id of each processed event, in src/data.ts:
// The ids of the payment events already processed, so the same one isn't processed twice.export const processedEvents = new Set<string>();A Set is a collection with no duplicates: has asks whether a value is in it, and add adds it. If the route already knows the id, it answers repeated: true without touching anything.
And it answers 200: with an error, the gateway would think the notification didn’t arrive and would send it again. The Set lives in memory, like the orders: it’s forgotten on restart, and in Phase 5 it will go to the database.
Idempotency-Key: a POST you can repeat
Section titled “Idempotency-Key: a POST you can repeat”Now, the other way around. The phone app creates an order, the response gets lost in a tunnel and the app retries. POST isn’t IdempotentSaid of an operation that leaves things in the same state whether you do it once or ten times. In HTTP, GET, PUT and DELETE are idempotent and POST isn’t, so repeating a POST can create two orders.Go to definition: the shop would create two orders.
The solution is the same as with the events. The app generates a unique value per order, usually a UUID (a random id, like the evt_… ones), and sends it in the Idempotency-Key header, the Idempotency keyA unique value the client sends in the Idempotency-Key header along with an operation, such as creating an order. If it repeats the request with the same key, the server returns the first response instead of doing it again.Go to definition. If it retries, it repeats the key.
POST /v2/orders HTTP/1.1Content-Type: application/jsonIdempotency-Key: 5f0c8a2e-luis-order
{"productId":2,"quantity":1}It isn’t a standard. It’s described in an IETF draft that expired in April 2026 without becoming an RFCRFC stands for Request for Comments.The public documents where the exact rules of internet protocols are written. HTTP/1.1, for example, is defined in RFCs 9110 and 9112.Go to definition. But it’s common practice: Stripe and other payment APIs have used it for years.
The middleware, src/middleware/idempotency.ts, stores what was answered to each key:
// What was answered to each key. In memory, like the data; in production it would go to the// database (Phase 5), and each key would expire after a day.interface StoredResponse { requestBody: string; status: ContentfulStatusCode; body: string; location: string | null;}
const stored = new Map<string, StoredResponse>();A Map stores key → value pairs, like a dictionary: get reads and set stores. For each key, the request’s body and what was answered: status code, body and Location. When a request arrives, its key is looked up:
export const idempotency: MiddlewareHandler = async (c, next) => { const key = c.req.header('Idempotency-Key'); if (key === undefined) return next(); // without a key, as always
const requestBody = await c.req.text(); const saved = stored.get(key); if (saved && saved.requestBody !== requestBody) { return problem(c, { type: problemType('reused-key'), title: 'That key was already used with other data', status: 422, detail: 'Use a new Idempotency-Key for each different operation', }); } if (saved) { // The same request again: the same response, without doing anything again. c.header and // c.body build it on this request's response, which already has its own X-Request-Id: it's // another request. c.header('Content-Type', 'application/json'); if (saved.location) c.header('Location', saved.location); c.header('Idempotent-Replayed', 'true'); return c.body(saved.body, saved.status); }- Without a key, everything goes on as always.
- The same key with another body is a client error:
422, what the draft proposes. - The same key with the same body is a retry: the stored response comes back, with
Idempotent-Replayed: true, a name from Stripe, not from the draft.
c.header and c.body build it on this request’s response, which already carries its own X-Request-Id: it’s another request, with its own id in the LogA text file where a program writes down what happens, one line for each thing. A web server’s has a line for each request it receives, and it’s the first thing you look at when something fails.Go to definition. Only what was stored is repeated from the first one.
If the key is new, the request goes on, and on the way back the response is stored:
await next();// Only what went well is stored: if it failed, the client can fix it and retry.if (c.res.ok) { const body = await c.res.clone().text(); const location = c.res.headers.get('Location'); // ok is a 2xx with a body, like 201: the as promises it to TypeScript, which sees a number. const status = c.res.status as ContentfulStatusCode; stored.set(key, { requestBody, status, body, location });}c.res.clone()copies the response before reading it: a body is a StreamData that arrives or is sent little by little, in chunks, instead of all at once, so a program can read it as it arrives. In a Node.js server, the body of a request is a stream.Go to definition, which can only be read once.- Only what went well is stored (
ok, a2xx): if it failed, the client can fix it and retry with the same key. as ContentfulStatusCodepromises TypeScript that it’s a status code with a body, which is whatc.bodyasks for (lesson 2). Here it’s true: it’s the201.
The route that creates orders, in src/contract.ts, adds the middleware and declares the header:
// With an Idempotency-Key, repeating the request doesn't create another order: it returns the same// response.export const createOrder = createRoute({ method: 'post', path: '/orders', tags: ['Orders'], summary: 'Creates an order', middleware: [idempotency] as const, request: { headers: z.object({ 'idempotency-key': z.string().optional().openapi({ example: 'b1c2d3e4-anas-order' }), }), body: jsonBody(newOrderSchema), }, responses: { 201: { ...asJson(orderSchema, 'The created order (or the same one, if the key is repeated)'), headers: withLocation, }, 422: invalidData, },});Try it
Section titled “Try it”The goal: for the shop to find out about payments without being fooled. For it to accept the good notification, reject the tampered and the fake ones, and not count the repeated one twice. And for a retried order not to be duplicated.
Write the code
Section titled “Write the code”You start from your project from lesson 6, “Serialization”:
- Create
src/signature.ts,src/middleware/verify-signature.tsandsrc/middleware/idempotency.ts. The last one starts by importing, withimport type,MiddlewareHandlerfrom'hono'andContentfulStatusCodefrom'hono/utils/http-status', andproblemandproblemTypefrom'../problems.ts'. - Change
src/config.ts(WEBHOOK_SECRET, with its message),src/schemas.ts,src/data.ts,src/contract.ts(the two routes and theirimportlines) andsrc/v2.ts(the webhook route, theimportofprocessedEventsand, at the end, the405for/webhooks/payments, like the others). - Add
WEBHOOK_SECRETto your.env.example:
# Copy this file as .env and change the values. .env isn't uploaded to Git: it's in .gitignore.PORT=3000LOG_LEVEL=info# A long text that's hard to guess. You can generate one with: openssl rand -hex 24ADMIN_TOKEN=change-this-to-a-long-token# The secret the shop shares with the payment gateway to sign the webhooks. A different one.WEBHOOK_SECRET=change-this-to-another-long-secretThe fake gateway and the new tests come in this lesson’s folder. Download it and copy what’s missing:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/16-webhooks.tar.gztar -xzf 16-webhooks.tar.gzcd shop-apimkdir -p scriptscp ../16-webhooks/scripts/payment-gateway.ts scripts/cp ../16-webhooks/test/webhooks.test.ts ../16-webhooks/test/openapi.test.ts ../16-webhooks/test/.env test/mkdir -p creates scripts if it doesn’t exist, and test/.env brings a secret for the tests. If you get stuck, compare your code with 16-webhooks. Add the gateway script to package.json (the highlighted line):
{ "name": "shop-api", "version": "1.0.0", "private": true, "type": "module", "engines": { "node": ">=24" }, "scripts": { "start": "node --env-file-if-exists=.env src/server.ts", "dev": "node --env-file-if-exists=.env --watch src/server.ts", "test": "node --env-file=test/.env --test", "check": "tsc --noEmit", "gateway": "node --env-file-if-exists=.env scripts/payment-gateway.ts" }, "dependencies": { "@hono/node-server": "2.1.8", "@hono/zod-openapi": "1.6.3", "@hono/zod-validator": "0.9.1", "@scalar/hono-api-reference": "0.12.10", "hono": "4.13.18", "pino": "10.4.0", "protobufjs": "8.8.0", "zod": "4.6.7" }, "devDependencies": { "@types/node": "26.6.4", "typescript": "7.0.2" }}This is what scripts/payment-gateway.ts does:
// The event carries its own id: if the shop receives it twice, it knows it's the same one.const event = { id: `evt_${randomUUID()}`, type: 'payment.completed', orderId };const body = JSON.stringify(event);const signature = sign(body, secret);
async function send(sentBody: string) { console.log(`→ POST /v2/webhooks/payments ${sentBody}`); const res = await fetch(`${shop}/v2/webhooks/payments`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Signature': signature }, body: sentBody, }); console.log(`← ${res.status} ${await res.text()}`);}
// --tamper: someone changes the order on the way, but the signature is the original body's.if (values.tamper) { await send(body.replace(`"orderId":${orderId}`, `"orderId":${orderId + 1}`));} else { await send(body);}// --repeat: the same event again, like when the gateway gets no response and retries.if (values.repeat) await send(body);randomUUID()gives the event a random id, andsignis the shop’s function: both sides calculate the same way.fetchsends the request (lesson 2 of Phase 3).→is what it sends, and←, what it gets back.--tamperchanges the order after signing, as someone on the way would.--repeatsends the same event twice.
Start without a secret
Section titled “Start without a secret”1. The server requires the secret
npm startWhat you will see:
> shop-api@1.0.0 start> node --env-file-if-exists=.env src/server.ts
Configuration: WEBHOOK_SECRET: WEBHOOK_SECRET is missingYour .env doesn’t have WEBHOOK_SECRET yet, and config.ts won’t let the server start without it. Better this way than finding out with the first payment.
2. A long secret
openssl rand -hex 24What you will see:
d79121847931c34ba344a4a2553bdc4783733bd950d011fcYours will be different. Add a WEBHOOK_SECRET= line to your .env with it after the =. Don’t make it your ADMIN_TOKEN: if one leaks, the other stays safe.
Start the server with npm run dev and leave that terminal open. Open another one in the project’s folder.
A payment, a trick and a repetition
Section titled “A payment, a trick and a repetition”Sample orders 21 to 25 are pending.
3. The gateway reports the payment for order 23
npm run gateway -- 23curl -w '\n' localhost:3000/v2/orders/23What you will see:
> shop-api@1.0.0 gateway> node --env-file-if-exists=.env scripts/payment-gateway.ts 23
→ POST /v2/webhooks/payments {"id":"evt_dde8a1b2-999a-43d1-a0b1-7ad90c176b0c","type":"payment.completed","orderId":23}← 200 {"received":"evt_dde8a1b2-999a-43d1-a0b1-7ad90c176b0c","repeated":false}{"id":23,"productId":3,"quantity":4,"status":"paid","createdAt":"2026-10-07T19:00:00.000Z"}What goes after -- reaches payment-gateway.ts, not npm. The shop answers 200 with repeated: false, and order 23 is now paid. Your event id will be different.
If you get fetch failed with ECONNREFUSED, the server isn’t running: check the other terminal. If you get 400 with invalid-signature, check signature.ts and verify-signature.ts: the signature is calculated on c.req.text() and has sha256= in front.
4. Someone changes the notification on the way
npm run gateway -- 24 --tampercurl -w '\n' localhost:3000/v2/orders/25What you will see:
> shop-api@1.0.0 gateway> node --env-file-if-exists=.env scripts/payment-gateway.ts 24 --tamper
→ POST /v2/webhooks/payments {"id":"evt_d00cdfd1-cae7-4381-8a49-b69d69eae8b9","type":"payment.completed","orderId":25}← 400 {"type":"https://shop.example/problems/invalid-signature","title":"The signature is not valid","status":400,"detail":"The X-Signature header does not match this body"}{"id":25,"productId":2,"quantity":2,"status":"pending","createdAt":"2026-10-08T09:00:00.000Z"}Order 24 was paid, but the body that arrives says 25. The signature is the original body’s and doesn’t match: 400, and order 25 stays pending.
5. The same notification, twice
npm run gateway -- 24 --repeatWhat you will see:
> shop-api@1.0.0 gateway> node --env-file-if-exists=.env scripts/payment-gateway.ts 24 --repeat
→ POST /v2/webhooks/payments {"id":"evt_778b57d0-1a63-4d46-a0e0-96949386a5b5","type":"payment.completed","orderId":24}← 200 {"received":"evt_778b57d0-1a63-4d46-a0e0-96949386a5b5","repeated":false}→ POST /v2/webhooks/payments {"id":"evt_778b57d0-1a63-4d46-a0e0-96949386a5b5","type":"payment.completed","orderId":24}← 200 {"received":"evt_778b57d0-1a63-4d46-a0e0-96949386a5b5","repeated":true}Two 200 responses with the same id, and repeated: true in the second: two acknowledgements, a single payment processed.
6. A fake notification, without a signature
curl -i --json '{"id":"evt_fake","type":"payment.completed","orderId":25}' localhost:3000/v2/webhooks/paymentsWhat you will see:
HTTP/1.1 400 Bad Requestcontent-type: application/problem+jsonvary: Originx-request-id: 793547ca-9fd8-47de-88c0-484673d3375bcontent-length: 167Date: Tue, 13 Oct 2026 15:39:04 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"type":"https://shop.example/problems/invalid-signature","title":"The signature is not valid","status":400,"detail":"The X-Signature header does not match this body"}The JSON is perfect, but without X-Signature it doesn’t get past the middleware: no free hoodie. Your x-request-id and your date will be different.
An order that is retried
Section titled “An order that is retried”Now you’re the phone app, and the network fails right when you create an order. Send the same request twice:
7. The same POST with the same key, twice
curl -i -w '\n' -H 'Idempotency-Key: 5f0c8a2e-luis-order' --json '{"productId":2,"quantity":1}' localhost:3000/v2/orderscurl -i -H 'Idempotency-Key: 5f0c8a2e-luis-order' --json '{"productId":2,"quantity":1}' localhost:3000/v2/ordersWhat you will see:
HTTP/1.1 201 Createdcontent-type: application/jsonlocation: /v2/orders/26vary: Originx-request-id: 30ee8e06-328c-4055-9d64-f3ef3bb9b0f5content-length: 94Date: Tue, 13 Oct 2026 15:39:04 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"id":26,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-13T15:39:04.175Z"}HTTP/1.1 201 Createdcontent-type: application/jsonidempotent-replayed: truelocation: /v2/orders/26vary: Originx-request-id: 1b5eb0c9-53fc-424b-a226-1d139b9e4fcdcontent-length: 94Date: Tue, 13 Oct 2026 15:39:04 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"id":26,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-13T15:39:04.175Z"}-H adds the header. Both responses are the same 201 with the same order 26, createdAt included. The second one carries idempotent-replayed: true, because it’s the stored response, and its own x-request-id. Your ids and your dates will be different.
8. The same key with other data
curl -w '\n' -H 'Idempotency-Key: 5f0c8a2e-luis-order' --json '{"productId":2,"quantity":3}' localhost:3000/v2/orderscurl -w '\n' 'localhost:3000/v2/orders?limit=2'What you will see:
{"type":"https://shop.example/problems/reused-key","title":"That key was already used with other data","status":422,"detail":"Use a new Idempotency-Key for each different operation"}[{"id":26,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-13T15:39:04.175Z"},{"id":25,"productId":2,"quantity":2,"status":"pending","createdAt":"2026-10-08T09:00:00.000Z"}]Three mugs instead of one, with the same key: 422. And the list confirms that the newest order is 26, and there’s only one.
To finish, npm test should end with fail 0: the new tests do the same as you, and a bit more.
Challenge: sign a notification by hand, without the gateway, with openssl and curl, and pay for order 25 with it. What does that tell you about your WEBHOOK_SECRET?Show answer
openssl dgst -sha256 -hmac calculates the same HMAC as createHmac. Put your secret in place of the example one:
SECRET=d79121847931c34ba344a4a2553bdc4783733bd950d011fcBODY='{"id":"evt_by_hand","type":"payment.completed","orderId":25}'SIGNATURE=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $NF}')curl -w '\n' -H "X-Signature: sha256=$SIGNATURE" --json "$BODY" localhost:3000/v2/webhooks/paymentscurl -w '\n' localhost:3000/v2/orders/25{"received":"evt_by_hand","repeated":false}{"id":25,"productId":2,"quantity":2,"status":"paid","createdAt":"2026-10-08T09:00:00.000Z"}printf '%s' doesn’t add the final line break, which would change the signature. awk '{print $NF}' keeps the last word: OpenSSL 3, the one on Linux, puts SHA2-256(stdin)= in front; LibreSSL, the one on macOS, doesn’t.
With the secret, anyone can be the gateway. That’s why it goes in .env, never in Git, and if it leaks, it’s changed on both sides.
You have already seen it
Section titled “You have already seen it”- “We’re confirming your payment…” That page, after you pay in an online shop, is usually waiting for the gateway’s webhook.
- “Don’t refresh the page or press back.” That warning exists because repeating the request could charge you twice. With an idempotency key, nothing is duplicated.
- The deployment of this site. In the Git lesson of Phase 1, GitHub “tells Cloudflare that
mainhas changed”: that notification is a webhook. Every repository has a Webhooks section in its settings.
Common mistakes
Section titled “Common mistakes”- Checking the signature on the JSON written again. A different space changes the signature: use the body exactly as it arrived.
- Comparing signatures with
===. UsetimingSafeEqual. - Answering a repeated notification with an error, or taking too long to answer. The gateway considers it failed and sends it again. A repeated one gets
200, and the long work comes later. - Idempotency keys that never expire. This shop keeps them forever; Stripe may delete them after 24 hours: a retry arrives within minutes.
- Keys that belong to nobody. Here, whoever repeats another client’s key gets the response stored for that other client. With users, the key is stored together with who sent it.
- Forgetting simultaneous requests. Two requests with the same key at the same time may both see it as new and create two orders. The draft proposes a
409for the second one while the first is still going.
Summary
Section titled “Summary”- A webhook is a
POSTanother service makes to your server when something happens. It arrives right away, without polling, but it needs a URL open to the internet. - The HMAC signature is a hash of the body with a secret only the two sides know. It’s checked on the body exactly as it arrived, with
timingSafeEqual; if it doesn’t match,400. - Notifications arrive at least once: write down each event’s id and answer
200to the repeated ones too, without processing them. Answer quickly; the long work, afterwards. - With
Idempotency-Key, the same key and the same body return the stored response; another body,422. It’s common practice, but only an IETF draft.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Validating webhook deliveries (GitHub): the same
sha256=signature, in several languages. - Receive Stripe events in your webhook endpoint and Idempotent requests (Stripe): signatures, retries, repeated events and
Idempotency-Keyin a payments API. - The Idempotency-Key HTTP Header Field (IETF): the draft, with its
400,409and422codes. - RFC 2104: HMAC: the definition of HMAC.
- createHmac and timingSafeEqual (Node.js).