Today I'm excited to announce @nestjs/webhooks, a new package for sending and receiving webhooks in Nest. Outgoing webhooks are dispatched in your database transaction, signed according to the Standard Webhooks spec, retried with backoff, and logged, so your partners can see and replay every delivery. Incoming webhooks are verified on their raw body, in constant time, and deduplicated, so a provider's retry never runs your handler twice.
In case you're not familiar with NestJS, it is a TypeScript Node.js framework that helps you build enterprise-grade efficient and scalable Node.js applications.
Let's dive right in! 🐈
Why a webhooks package?
Webhooks look like the simplest integration there is. Something happens, you POST some JSON to a URL. Done.
Except it rarely is. Let's say you run an online store for cat food and supplies, and a reseller wants to be notified when their orders ship or get cancelled, instead of polling your API. A fetch() call after the order is saved gets lost if the process crashes. Call it inside the transaction, and it fires for an order that later rolls back. Retry on failure, and the partner receives a duplicate without knowing it is one. Then every partner has to write a verifier for your homemade signature, nobody knows which deliveries actually succeeded, and dead endpoints keep getting hammered forever. Oh, and since the partner gives you the URL, it might as well point at your cloud metadata endpoint. 🙃
Receiving webhooks has its own list of traps. The signature gets checked against a body your framework already re-serialized, the comparison isn't constant-time, there's no timestamp window to stop replays, and when the provider redelivers an event, your handler marks the order as paid twice.
@nestjs/webhooks takes care of both sides.
Getting started
First, install the package:
$ npm i --save @nestjs/webhooksOutgoing webhooks travel through @nestjs/outbox, so you register both modules, along with a store for each. Endpoints, messages, and the full delivery log live in your own database (PostgreSQL or MySQL):
@Module({ imports: [ DrizzleModule.forRootAsync({ /* ... */ }), OutboxModule.forRootAsync({ /* ... */ }), WebhooksModule.forRootAsync({ useFactory: () => ({ eventTypes: ['order.shipped', 'order.cancelled'], retry: { attempts: 10, backoff: { delay: '5s', factor: 4, maxDelay: '1d' } }, disableEndpointAfter: '5d', delivery: { timeout: '15s' }, }), }), ], providers: [ { provide: PostgresWebhookStore, inject: [getDrizzleToken(), WebhooksStorage], useFactory: (db: Database, storage: WebhooksStorage) => new PostgresWebhookStore({ executor: fromDrizzle(db) }, storage), }, // ...and the PostgresOutboxStore, registered the same way ],})export class AppModule {}eventTypes lists every event you send, and dispatch() refuses anything else, so a typo never reaches a partner. With these retry settings, a delivery is retried for about two days before giving up, and an endpoint that keeps failing for five days is disabled.
Let partners subscribe
Partners manage their own endpoints through your API. The WebhookEndpoints service does the heavy lifting, and every call is scoped to a tenant, so one partner can never see or touch another one's endpoints:
@Post()create(@CurrentPartner() partner: Partner, @Body() dto: CreateEndpointDto) { return this.endpoints.create(dto, { tenant: partner.id });}When an endpoint is created, the server generates a signing secret (whsec_..., 32 random bytes) and returns it exactly once. Listing endpoints never returns it again.
URLs are validated as well: https only, no embedded credentials, and no private network addresses, localhost, or cloud metadata hosts. You can relax these rules for local development (allowHttp, allowPrivateNetworks), but in production they stay on.
Send webhooks after the commit
Here's the important part. Dispatching a webhook is part of your transaction:
async cancelOrder(partner: Partner, id: string, reason: string) { await this.db.transaction(async (tx) => { const order = await this.findForUpdate(tx, partner, id); if (order.status === 'shipped' || order.status === 'cancelled') { throw new ConflictException(`Order ${id} can no longer be cancelled`); } await tx.update(orders).set({ status: 'cancelled' }).where(eq(orders.id, id)); await this.webhooks.dispatch(tx, { type: 'order.cancelled', tenant: partner.id, data: { orderId: id, reason }, }); }); this.webhooks.notify();}Under the hood, dispatch() adds a message to the outbox in the same transaction. If the transaction rolls back, nothing is sent. Once it commits, the message fans out to every enabled endpoint of that partner subscribed to order.cancelled, and it's delivered even if the process crashes a millisecond later.
Every request is signed according to the Standard Webhooks spec, with webhook-id, webhook-timestamp, and webhook-signature headers. Which means your partners don't have to write a custom verifier. They can use any Standard Webhooks library in any language, or, if they also use Nest, @nestjs/webhooks itself.
Retries, the delivery log, and replay
A 2xx is a success, and anything else is a failed attempt. That includes redirects, which are never followed. Failed attempts are retried with exponential backoff, and the client honors Retry-After. When an endpoint answers with 429 or 503, it's paused, while deliveries to other partners keep flowing. A 410 Gone ends the delivery and disables the endpoint right away.
Every attempt is logged with the status code, duration, the first 4 KB of the response body, and the error. So when a partner says "we never received it", you don't have to dig through logs. You can show them the delivery, or better yet, let them see it themselves and replay it through your API. A replay resends the same body with the same webhook-id, so their deduplication keeps working.
Receiving webhooks
Now let's flip it around. Your store also receives webhooks from a payment provider. First, tell the module who's sending them:
receivers: { payments: { scheme: 'standard', secret: process.env.PAYMENTS_WEBHOOK_SECRET }, carrier: { scheme: 'stripe', header: 'Carrier-Signature', secret: process.env.CARRIER_WEBHOOK_SECRET, },},Then verify them with a single decorator:
@Post('webhooks/payments')@VerifyWebhook('payments')async handle(@IncomingWebhook() webhook: IncomingWebhookContext<PaymentEvent>) { await this.db.transaction((tx) => webhook.processInTransaction(tx, () => this.ordersService.markPaid(tx, webhook.payload)), );}@VerifyWebhook() checks the signature against the raw request body (so remember to create the app with { rawBody: true }), compares it in constant time, and rejects timestamps more than five minutes off, which stops replayed requests. A failure is a plain 401, and the actual reason only goes to a verification-failed event, so attackers learn nothing.
processInTransaction() records the webhook id in the same transaction as your business write. If the provider sends the same event again, the handler doesn't run, and the provider gets an empty 200. If the handler throws, nothing is recorded, and the provider's retry gets another chance.
Besides Standard Webhooks, the package supports Stripe-style and GitHub signatures out of the box, and you can add any other provider's scheme by extending WebhookSignatureScheme.
Rotating secrets
Secrets leak, and they should be rotated anyway. When a partner rotates an endpoint's secret, the old one keeps signing for 24 hours, and each delivery carries both signatures in the meantime, so nothing breaks while they update their configuration. For your own receivers, just list the old and the new secret during the rotation. And with encryption configured, endpoint secrets are encrypted at rest as well.
Observability
Every important moment is published on WebhooksEvents.events$ and on diagnostics channels (nestjs:webhooks:delivered, nestjs:webhooks:endpoint-disabled, and so on): delivered, retry scheduled, delivery failed, endpoint disabled, destination blocked, and verification failed. Alert on disabled endpoints (and let the partner know!), and keep an eye on failures. With NestJS Observe, you can turn these events into custom metrics.
Testing
The package ships with an in-memory transport for outgoing webhooks, and a signWebhook() helper in @nestjs/webhooks/testing that produces valid (or deliberately tampered) signatures, so you can test your receivers end to end without a real provider.
Try it today!
$ npm i --save @nestjs/webhooksThe new Webhooks chapter in the official documentation covers everything above in depth, including TypeORM, Prisma, and MySQL setups, GitHub and custom signature schemes, delivery guarantees, and a production checklist. Give it a try, and please open an issue if anything gets in your way!
Happy coding! 🐈
Learn NestJS - Official NestJS Courses 📚
Level-up your NestJS and Node.js ecosystem skills in these incremental workshop-style courses, from the NestJS Creator himself, and help support the NestJS framework! 🐈🚀 The NestJS Fundamentals Course is now LIVE and 25% off for a limited time!
🎉 NEW - NestJS Course Extensions now live!
- NestJS Advanced Concepts Course now LIVE!
- NestJS Advanced Bundle (Advanced Architecture and Advanced Concepts) now 22% OFF!
- NestJS Microservices now LIVE!
- NestJS Authentication / Authorization Course now LIVE!
- NestJS GraphQL Course (code-first & schema-first approaches) are now LIVE!
- NestJS Authentication / Authorization Course now LIVE!
