Express.js / Advanced: resource, write and release contracts / Lesson 21
Webhook signatures and duplicate delivery
Verify a signed raw request and design durable, replay-safe processing for a provider’s webhook.
On this page
Lesson goals
- Preserve the bytes required by a provider’s signature contract.
- Separate signature verification from event deduplication.
- Test tampering, duplicate delivery and recovery.
Read the provider contract
A webhook is an inbound request initiated by another system. Providers differ in signature format, timestamp rules, retry policy and event identifiers. Follow the specific provider’s documentation rather than assuming one HMAC format. Bound request size and processing time, protect the signing secret, and treat headers and body as untrusted until verification succeeds. A valid signature does not by itself prevent replay of the same valid delivery.
Preserve the signed bytes
The route-specific express.raw parser supplies a Buffer for the configured content type. Mount it before a general JSON parser consumes the same webhook request, and follow the provider’s exact byte and content-type contract. The fragment is illustrative and assumes an application-defined handler. A size limit and parser configuration protect only the layers where they are applied; also review proxy limits and provider behavior.
app.post('/webhook', express.raw({ type: 'application/json', limit: '64kb' }), handleWebhook);
app.use(express.json());
Mount this route before a general parser for the same request. The application-defined handler must verify, validate and persist the event.
Compare a synthetic signature
The helper demonstrates HMAC-SHA256 and a timing-safe comparison for a simple hexadecimal signature format. It rejects malformed length and characters before converting to equal-length buffers. This is not a complete provider verifier: include the provider’s documented prefix, timestamp, rotation and signed payload format, use a secret from controlled configuration and reject mismatches before parsing or applying effects. Never log the secret or signature.
const { createHmac, timingSafeEqual } = require('node:crypto');
function validSignature(secret, body, supplied) {
if (!/^[0-9a-f]{64}$/.test(supplied)) return false;
const actual = Buffer.from(supplied, 'hex');
const expected = createHmac('sha256', secret).update(body).digest();
return timingSafeEqual(expected, actual);
}
The helper assumes a simple lowercase hexadecimal protocol; real providers may sign different bytes and include timestamps or prefixes.
Persist intent and deduplicate
After signature verification, validate the event type and schema, then record a stable event ID and processing intent under a database uniqueness constraint. Associate the marker and database effect transactionally. Acknowledge according to the provider contract only after the durability boundary the application promises. External services need their own idempotency or reconciliation; a database marker alone cannot atomically control a separate provider.
Test failure and recovery
Use synthetic secrets and payloads to test a valid request, changed byte, missing or malformed signature, expired timestamp where applicable, and duplicate event. Check response and durable state, including no effect on rejection. Simulate failure after acceptance and before completion, then retry. An in-process test cannot prove proxy body limits, actual provider retries or broker recovery; verify those in an approved integration environment.
Common errors and fixes
A valid signature fails after JSON parsing
- Why it happens
- The verified bytes differ from the provider’s signed representation.
- How to fix it
- Verify the raw documented bytes before parsing.
- Prevent it next time
- Test a provider fixture and a one-byte change.
A signed event is applied twice
- Why it happens
- Signature validity was mistaken for replay protection.
- How to fix it
- Enforce a stable event ID and idempotent effect.
- Prevent it next time
- Test sequential and concurrent duplicate deliveries.
An accepted event is lost on restart
- Why it happens
- The response acknowledged work stored only in memory.
- How to fix it
- Persist the intent before acknowledging as the contract requires.
- Prevent it next time
- Simulate a process stop and recovery.
2 practice exercises
1. Why place the raw parser before a general JSON parser for this route?
Show worked solution
The provider may sign the exact original body bytes. A JSON parser can consume or transform the representation before verification. Scope and order the raw parser according to the provider contract, then parse only after validation.
2. The same valid event arrives twice. What should the handler do?
Show worked solution
Verify each delivery, use the provider’s stable event ID to detect an already accepted event, and avoid repeating its effect. Return the provider-compatible response and test both simultaneous and sequential retries.
Key takeaways
- Verify exact provider-specified bytes before processing.
- Durable acceptance and replay-safe effects are separate from signature validation.