--- title: "Webhooks" description: "Receive provider webhooks with raw-body signature verification, typed event catalogs, Next.js route adapters, and idempotent handlers." url: "https://www.beignetjs.com/webhooks" markdown_url: "https://www.beignetjs.com/markdown/webhooks.md" framework_version: "0.0.65" documentation_scope: "current-checkout" source_revision: "ba3f49c103f3c4515e8ca14e07651fe5b83e2cec" source_modified: true --- # Webhooks For a complete implementation, follow [Receive a GitHub webhook](https://www.beignetjs.com/markdown/guides/github-webhook.md). It verifies signed issue events, persists opened issues once, and tests invalid requests and redelivery against SQLite. Use `@beignet/core/webhooks` when an app needs to receive external HTTP events without scattering raw-body parsing, signature checks, event validation, and handler routing through route files. Inbound webhooks are not ordinary JSON API routes. Signature verification usually depends on the exact raw request body, so the adapter must read the body before it is parsed. ## Choose a route helper Use `createPaymentWebhookRoute(...)` from `@beignet/next` for app billing flows backed by `ctx.ports.payments`. This is the route generated by `beignet make payments`; it verifies through `ctx.ports.payments.verifyWebhook(...)` and passes your handler a normalized `PaymentWebhookEvent` from `@beignet/core/payments`. Use `createWebhookRoute(...)` for generic inbound webhooks backed by a typed `defineWebhook(...)` event catalog. Provider verifier packages such as `@beignet/webhooks-github` and `@beignet/webhooks-stripe` adapt vendor signature rules to this generic webhook primitive. Use the Stripe webhook verifier for non-payment Stripe events, or for apps that deliberately model Stripe through a generic webhook catalog instead of the payments port. ## Define a webhook Define webhook event catalogs near the feature that owns the workflow: ```typescript // features/integrations/webhooks.ts import { defineWebhook } from "@beignet/core/webhooks"; import { z } from "zod"; type StripeWebhookPayload = { id: string; object: string; }; const stripeWebhookPayloadSchema = z.custom( (value): value is StripeWebhookPayload => typeof value === "object" && value !== null && typeof (value as { id?: unknown }).id === "string" && typeof (value as { object?: unknown }).object === "string", ); export const stripeWebhook = defineWebhook("integrations.stripe", { provider: "stripe", events: { "customer.created": stripeWebhookPayloadSchema, "charge.dispute.created": stripeWebhookPayloadSchema, }, }); ``` The event catalog validates the payload passed to your handler. The verifier owns authenticity and converts provider-specific requests into Beignet webhook events. Install vendor verifier packages when a provider has signature details that should not be reimplemented in app code: ```bash bun add @beignet/webhooks-stripe stripe @beignet/core bun add @beignet/webhooks-github @beignet/core ``` `@beignet/webhooks-stripe` supports Stripe SDK 22 and 23. Verification preserves the received event's API version in `event.metadata.apiVersion`; it does not convert payloads to the installed SDK's version. Custom verifier clients receive a single signature string. Configure webhook endpoint versions in Stripe and validate your catalog schemas against their payloads. See [Stripe SDK and API versions](https://www.beignetjs.com/markdown/payments.md#stripe-sdk-and-api-versions) before upgrading an existing integration. ## Expose a Next.js route Use `createWebhookRoute(...)` from `@beignet/next` for raw-body route handling: ```typescript // app/api/webhooks/stripe/route.ts import { createWebhookRoute } from "@beignet/next"; import { createStripeWebhookVerifier } from "@beignet/webhooks-stripe"; import { stripeWebhook } from "@/features/integrations/webhooks"; import { handleStripeWebhookUseCase } from "@/features/integrations/use-cases"; import { env } from "@/lib/env"; import { getServer } from "@/server"; export const runtime = "nodejs"; const stripeWebhookVerifier = createStripeWebhookVerifier({ secret: () => env.STRIPE_WEBHOOK_SECRET, }); export const { POST } = createWebhookRoute({ server: getServer, webhook: stripeWebhook, maxBodyBytes: 1024 * 1024, verify: ({ input }) => stripeWebhookVerifier.verify(input), handle: async ({ ctx, event }) => { await handleStripeWebhookUseCase.run({ ctx, input: event }); return { status: 200, body: { received: true } }; }, }); ``` The raw body limit defaults to 1 MiB. Requests above `maxBodyBytes` return 413 before server resolution, hooks, context creation, verification, or fulfillment. Keep the limit aligned with the webhook provider's documented maximum payload size. By default, `createWebhookRoute(...)` rejects verified event types that are not in the catalog and returns a 400. Set `allowUnknownEvents: true` only for broad provider endpoints that intentionally acknowledge valid event types your app does not handle. ```typescript export const { POST } = createWebhookRoute({ server: getServer, webhook: stripeWebhook, verify: ({ input }) => stripeWebhookVerifier.verify(input), allowUnknownEvents: true, handle: async ({ event }) => { if (event.type !== "customer.created") { return { status: 200, body: { ignored: true } }; } return { status: 200, body: { received: true } }; }, }); ``` When the `server` option is a real Beignet server (anything exposing `rawRoute(...)` — a `NextServer` or core `ServerInstance`), the route runs inside the full hooks pipeline: rate limiting, CORS, logging, error reporting, and instrumentation all apply, and the request shows up in devtools like any contract route. Declare metadata-driven hook behavior with the `pipeline` option: ```typescript export const { POST } = createWebhookRoute({ server: getServer, webhook: githubWebhook, verify: ({ input }) => githubWebhookVerifier.verify(input), pipeline: { metadata: { rateLimit: { max: 600, windowSec: 60 } }, }, }); ``` Minimal test fakes that only implement `createRequestContext` keep the direct flow, so route modules stay executable under the app's test runner without a booted server. The same applies to `createPaymentWebhookRoute`, `createScheduleRoute`, and `createOutboxDrainRoute`. For endpoints these factories do not cover — third-party callback routes such as collaboration room auth — build the handler with `server.rawRoute(...)` directly; see [Server](https://www.beignetjs.com/markdown/server.md#raw-routes). Use the context-aware `verify` option when verification depends on app ports. Otherwise, create a reusable verifier in the route or server layer and pass it through `verify`. ## Where verifiers live Feature webhook definitions stay provider-free. A `defineWebhook(...)` catalog in `features//` is contract-reachable code, and contract-reachable code cannot import `@beignet/provider-*` packages — `beignet lint` enforces this dependency direction. Attach provider verifiers such as `createStripeWebhookVerifier(...)` and `createGitHubWebhookVerifier(...)` at the route boundary through the `verify` option of `createWebhookRoute(...)`, as the examples on this page do. The inline `verifier:` option on `defineWebhook(...)` is reserved for the core verifiers — `createHmacWebhookVerifier(...)` and `createMemoryWebhookVerifier(...)` from `@beignet/core/webhooks` — and for tests. ## GitHub webhooks GitHub event names and delivery IDs live in headers, so use `@beignet/webhooks-github` instead of the generic HMAC verifier: ```typescript // features/integrations/webhooks.ts import { defineWebhook } from "@beignet/core/webhooks"; import { z } from "zod"; export const githubWebhook = defineWebhook("integrations.github", { provider: "github", events: { issues: z.object({ action: z.string(), issue: z.object({ number: z.number() }), repository: z.object({ full_name: z.string() }), }), }, }); ``` ```typescript // app/api/webhooks/github/route.ts import { createWebhookRoute } from "@beignet/next"; import { createGitHubWebhookVerifier } from "@beignet/webhooks-github"; import { githubWebhook } from "@/features/integrations/webhooks"; import { handleGitHubWebhookUseCase } from "@/features/integrations/use-cases"; import { env } from "@/lib/env"; import { getServer } from "@/server"; export const runtime = "nodejs"; const githubWebhookVerifier = createGitHubWebhookVerifier({ secret: () => env.GITHUB_WEBHOOK_SECRET, }); export const { POST } = createWebhookRoute({ server: getServer, webhook: githubWebhook, verify: ({ input }) => githubWebhookVerifier.verify(input), handle: async ({ ctx, event }) => { await handleGitHubWebhookUseCase.run({ ctx, input: event }); return { status: 200, body: { received: true } }; }, }); ``` The verifier reads `X-Hub-Signature-256`, `X-GitHub-Delivery`, and `X-GitHub-Event`, then verifies the raw body before parsing JSON. ## Generic HMAC verification For simple JSON webhooks that use an HMAC signature over the raw body, use the generic verifier: ```typescript import { createHmacWebhookVerifier, defineWebhook, } from "@beignet/core/webhooks"; import { z } from "zod"; export const issueWebhook = defineWebhook("issues.provider", { provider: "provider", events: { "issue.created": z.object({ id: z.string(), type: z.literal("issue.created"), issueId: z.string(), title: z.string(), }), }, verifier: createHmacWebhookVerifier({ secret: process.env.PROVIDER_WEBHOOK_SECRET ?? "", signatureHeader: "x-provider-signature", signaturePrefix: "sha256=", timestamp: { header: "x-provider-timestamp", toleranceSec: 300, }, }), }); ``` `createHmacWebhookVerifier(...)` expects a JSON payload with string `id` and `type` fields by default. Use `eventIdPath` and `eventTypePath` when a provider uses different names. Configure `timestamp` when the provider signs a timestamp header or payload field. Header mode verifies the HMAC over the exact `.` bytes; payload mode verifies the raw body, which already contains the timestamp. Beignet rejects missing, malformed, stale, and too-far-future timestamps before the handler runs. ## Handling safely Webhook providers retry. Handlers should be idempotent: ```typescript await runIdempotently(ctx.ports.idempotency, { namespace: "billing.handlePaymentWebhook", key: event.id, scope: event.provider, fingerprint: event.type, run: () => applyBillingEvent(ctx, event), }); ``` For workflows that must survive process restarts, record a domain event or job through the outbox after verification and acknowledge the provider quickly. Keep long-running work out of the route handler. The route helpers use HTTP status codes as the provider retry contract: - Invalid signatures, malformed payloads, and strict unknown-event failures return 400. - Verified duplicate events should be acknowledged after idempotency confirms the original result. - Handler failures return 500 so at-least-once webhook providers can retry. - For broad provider endpoints configured with `allowUnknownEvents: true`, verified event types your app does not handle should usually be acknowledged and ignored. ## Testing Use the memory verifier for route and use-case tests: ```typescript import { createMemoryWebhookVerifier, defineWebhook, verifyWebhook, } from "@beignet/core/webhooks"; const verifier = createMemoryWebhookVerifier(); verifier.queue({ id: "evt_1", type: "issue.created", payload: { issueId: "issue_1" }, }); const webhook = defineWebhook("issues.provider", { verifier }); const event = await verifyWebhook(webhook, { rawBody: "{}", headers: {}, }); ``` ## API reference - [`createGitHubWebhookVerifier`](https://www.beignetjs.com/typedoc/functions/_beignet_webhooks-github.createGitHubWebhookVerifier.html) - [`createStripeWebhookVerifier`](https://www.beignetjs.com/typedoc/functions/_beignet_webhooks-stripe.createStripeWebhookVerifier.html) ## Related pages - [Ports and adapters](https://www.beignetjs.com/markdown/ports.md) for app-facing dependency boundaries. - [Payments](https://www.beignetjs.com/markdown/payments.md) for Stripe-backed billing webhooks. - [Idempotency](https://www.beignetjs.com/markdown/idempotency.md) for retry-safe webhook handlers. - [Outbox](https://www.beignetjs.com/markdown/outbox.md) for durable post-verification work. ## Web Fetch hosts Use `createWebhookRoute` and `createPaymentWebhookRoute` from `@beignet/web` for Bun or another Fetch host. Mount the returned method handlers in the host entrypoint and reuse the app's assembled server or ports. Next apps import the corresponding helper from `@beignet/next`. See [operational HTTP handlers](https://www.beignetjs.com/markdown/server.md#operational-http-handlers) for mounting, context, and lifecycle behavior.