NestJS / Advanced: lifetime and distributed-work evidence / Lesson 21
Raw-body webhooks and replay safety
Preserve signed request bytes in Nest and design verified, durable processing for repeated webhook events.
On this page
Lesson goals
- Enable and read the raw request body for a supported adapter.
- Verify a provider-specific signature before processing.
- Test tampering, duplicate events and recovery.
Identify the provider contract
A webhook is an inbound request from another system. Providers define different signature formats, timestamp tolerances, event identifiers and retry rules. Follow the specific provider’s documentation, bound request size and processing time, and keep secrets in controlled configuration. A signed message can still be replayed, so signature verification and duplicate-effect prevention are separate responsibilities.
Preserve the original body
The bootstrap fragment enables Nest’s rawBody option for an existing application module. The documented feature depends on the built-in body parser and supported platform adapter; verify the application’s actual parser configuration and size limits. Reading the raw body preserves the bytes needed by a provider that signs them, but retaining and parsing request data still consumes resources. Review proxy limits and avoid logging the body or signature.
const app = await NestFactory.create(AppModule, { rawBody: true });
await app.listen(3000);
AppModule and bootstrap are application-specific. Check parser and platform-adapter support for the installed Nest version.
Verify before processing
The controller sketch checks that raw bytes and a signature exist, then delegates to an application-defined provider verifier before accepting the event. The verifier must implement the provider’s exact signed bytes, timestamp, encoding and key rotation rules, using a safe comparison where appropriate. This fragment is not a complete authentication implementation. After verification, validate the event schema and type before any business effect.
@Post('webhook')
async receive(@Req() req: RawBodyRequest<Request>) {
const signature = req.header('x-signature');
if (!req.rawBody || !signature || !verifyProvider(req.rawBody, signature)) {
throw new UnauthorizedException();
}
await acceptEvent(req.rawBody);
return { accepted: true };
}
verifyProvider and acceptEvent must implement the real provider contract and durable policy. The fragment omits provider-specific authentication details.
Record accepted work durably
Persist a stable provider event identifier and processing intent under a uniqueness constraint before acknowledging according to the provider’s contract. Associate a database marker and database effect in one transaction where appropriate. A worker can crash after an external effect but before acknowledgement; use provider-supported idempotency or reconciliation for that separate system. In-memory callbacks or an HTTP 200 alone do not make the work durable.
Exercise failures and replay
Use synthetic payloads and keys to test a valid request, a one-byte change, a missing or malformed signature, a stale timestamp if specified, and duplicate delivery. Check status and durable state, including no effect after rejection. Simulate a stop after acceptance and verify recovery. An in-process test cannot establish provider retries, proxy body limits or the broker’s production behavior; test those boundaries separately.
Common errors and fixes
A valid signature fails after JSON transformation
- Why it happens
- The verifier used reconstructed JSON rather than the signed bytes.
- How to fix it
- Verify the provider’s exact raw representation.
- Prevent it next time
- Test a provider fixture and a changed byte.
A signed event produces a duplicate effect
- Why it happens
- Signature validation was mistaken for replay protection.
- How to fix it
- Use a stable event identifier and idempotent processing.
- Prevent it next time
- Test sequential and concurrent duplicate deliveries.
A job is lost after acknowledgement
- Why it happens
- Accepted work was kept only in process memory.
- How to fix it
- Persist the accepted intent before the promised acknowledgement.
- Prevent it next time
- Simulate termination and recovery.
2 practice exercises
1. Why might serializing a parsed JSON body invalidate a signature?
Show worked solution
Whitespace, key order or encoding can differ from the original signed bytes. Preserve and verify the exact representation specified by the provider, then parse and validate the event.
2. The same valid event arrives twice. What should happen?
Show worked solution
Verify each delivery, use the provider’s stable event ID to find an already accepted event, and avoid repeating the effect. Return the provider-compatible response and test concurrent retries.
Key takeaways
- Raw-body signature checks require the provider’s exact contract.
- Durable acceptance and idempotency protect different failure boundaries.