Inbound webhooks

A webhook is a request an external service (a shop platform, a payment provider) sends to your app when something happens there: an order was paid, a subscription ended. It is the highest-risk handler an app has, because it changes data on behalf of nobody: there is no cookie, no bearer token and no user, only a signature the sender made with a secret you share. createWebhookRoute (@dash/server) does the parts every app would otherwise get subtly wrong: it checks the signature on the raw bytes, bounds the body, remembers which events it has seen, and hands your code a verified event.
ts
// src/collections/index.ts — once per app, like sessionCollection
import { webhookEventCollection } from "@dash/server";
export const appCollections = [/* ... */, webhookEventCollection];
ts
// src/app/api/webhooks/fourthwall.ts
import { createWebhookRoute, hmacSha256 } from "@dash/server";
import { data } from "@dash/generated/data";

export const POST = createWebhookRoute({
  name: "fourthwall",
  data,
  secret: () => process.env.FOURTHWALL_WEBHOOK_SECRET?.split(","),
  verify: hmacSha256({ header: "X-Fourthwall-Hmac-SHA256", encoding: "base64" }),
  events: {
    ORDER_PLACED: async (event, { data, id }) => {
      await data.create({
        collection: "orders",
        overrideAccess: true, // there is no user on a webhook: say so
        data: { externalId: id /* ... */ },
      });
    },
  },
});
That is the whole integration. The file path is the URL (POST /api/webhooks/fourthwall); give that HTTPS URL, and the signing secret, to the sender. Run bun run codegen and commit the new migration for the webhook_events table.

What happens to a request, in order

Step
Outcome
Why this order
Read the body as bytes, at most maxBodyBytes (default 1 MiB)413 over the limit, without reading furtherBounds what an unauthenticated caller can make you buffer. Content-Length is checked first; a body without one is counted as it streams.
Resolve the secret(s)500 if none is configuredMisconfiguration must fail closed, never accept unsigned requests.
Verify the signature on those bytes401, empty bodyNothing is parsed, looked up or logged from a body that is not yet trusted. A verifier that throws counts as a refusal.
Parse JSON, validate (schema), read id and type400Only now is the payload the sender's. A signed but malformed event is a sender bug; it is not stored.
Type not served by events/handle200, nothing recordedA sender must not retry forever for events the app ignores.
Claim the event id (below)duplicate 200; in flight 409The handler never runs without a durable record.
Run the handlerthrows → release the claim, 500A failed event must be retried, so it must not look done.
Mark the event done200If only this write fails the handler already succeeded: acknowledge anyway.
Responses have no body. Treat only 200 as delivered: Fourthwall, for one, counts any other status (and anything slower than about two seconds) as a failed delivery and retries it.

Verifying: verify and secret

A verifier is (rawBody: Uint8Array, request, secrets) => boolean | Promise<boolean>. Built-ins use WebCrypto HMAC-SHA-256 and crypto.subtle.verify (a constant-time comparison); every secret and every candidate signature is tried, so timing does not say which matched. They need nothing but the Web platform, so they run on Workers.
Scheme
Verifier
Fourthwall: base64 digest of the raw body in X-Fourthwall-Hmac-SHA256hmacSha256({ header: "X-Fourthwall-Hmac-SHA256", encoding: "base64" })
GitHub: sha256=<hex>hmacSha256({ header: "X-Hub-Signature-256", encoding: "hex", prefix: "sha256=" })
Stripe-style: t=<seconds>,v1=<hex> over "<t>.<body>", with a tolerance windowtimestampedHmacSha256({ header: "Stripe-Signature", toleranceSeconds: 300 })
Timestamp in its own header (Slack)hmacSha256({ header: "X-Slack-Signature", encoding: "hex", prefix: "v0=", timestampHeader: "X-Slack-Request-Timestamp", signedPayload: "v0:{timestamp}:{body}" })
Anything elseyour own (body, request, secrets) => boolean
secret is a function, called on every request: a Worker has its environment only once it serves a request, so secret: () => process.env.X reads it at the right time where a plain string read at import would be undefined. Return an array to accept several secrets at once: during a rotation, deploy NEW,OLD, switch the sender to the new secret, then deploy NEW. Empty values are ignored, and no secret at all is a 500.A timestamp option (timestampHeader, or timestampedHmacSha256) refuses requests outside the window in either direction, which bounds how long a captured request can be replayed. A sender that does not sign a time (Fourthwall) leaves replay protection to the event-id record below.

Testing without the sender

ts
import { signWebhook, hmacSha256 } from "@dash/server";
const verify = hmacSha256({ header: "X-Fourthwall-Hmac-SHA256", encoding: "base64" });
const body = JSON.stringify({ id: "evt_1", type: "ORDER_PLACED", data: {} });
const headers = await signWebhook(verify, { body, secret: "test-secret" });
const res = await POST(new Request("http://x/api/webhooks/fourthwall", { method: "POST", body, headers }));
signWebhook returns the headers the built-in verifier expects (pass timestamp to test the tolerance window). It is a function, not a framework: a scratch script is enough.

Exactly what "once" means

Senders retry (a non-200, a timeout, a lost response), so one event arrives more than once. The route gives you at-least-once handler execution with a dedupe record, not exactly-once; write handlers so running twice is harmless (an upsert keyed by the event or order id, not a blind insert).The record lives in webhook_events (webhookEventCollection, access fully closed, only touched with overrideAccess; it stores ids, type and timestamps, never the payload). Its primary key is sha256(name, event id) plus an attempt number, and the database's primary-key constraint is what arbitrates races. That is why it works the same on D1, Postgres and the memory adapter.
  • First delivery. The claim row is created before the handler runs, then marked done when it returns. If the claim cannot be written (database down, collection not registered) the answer is 500 and the handler does not run.
  • Duplicate after success. 200, handler not run.
  • Handler throws. The claim is deleted and the answer is 500. The event is not marked done, so the sender's retry runs it as a fresh first delivery. If even the delete fails, the lease (below) lets a later delivery take over.
  • Two deliveries at the same time. Both try to create the same row; exactly one wins and runs. The other gets 409 with Retry-After: 5: not 200, because if the winner then fails, the sender must still be retrying something. By the retry it is done.
  • An attempt that died (process killed, Worker evicted) leaves a processing row with a lease (dedupe.leaseSeconds, default 60). While the lease holds, other deliveries get 409. After it expires the next delivery creates attempt 2, and context.attempt says so. Set the lease above the longest the handler can take: a handler still running when its lease lapses can run a second time alongside the new attempt.
  • Retention. Rows expire after dedupe.retentionSeconds (default 7 days) and a few expired rows are deleted whenever a new event is recorded, so there is no cron. Retention must outlast the sender's retry schedule; an event redelivered after its row was pruned runs again.
Events the route ignores (unlisted type) are acknowledged without a record: there is nothing to dedupe because nothing runs.

The handler: no user

ts
handle(event, { data, user, request, rawBody, source, id, type, attempt })
user is always null, and getAppDataUser(request) returns null too (even if the server would otherwise bind a public owner). Every Local API call needs overrideAccess: true, written out (hard rule 5): a webhook is the system acting on a verified signature, and collection access rules are written for users. Decide in the handler what the event is allowed to change; validate its fields as input from the outside (a schema option takes zod or any Standard Schema and answers 400 for a bad shape).
  • Return normally to acknowledge, including "nothing to do": an unknown order id a retry cannot fix should be logged and acknowledged, not thrown.
  • Throw to be retried.
  • events maps type → handler; handle serves every type events does not list; with neither listed for a type the event is ignored. id and type default to the event's id and type fields; pass id: (event) => ... / type: (event) => ... for other shapes.
  • Keep it fast. Fourthwall wants an answer within about two seconds. Write the row, return; do the slow part afterwards.
Long work on Workers. runInBackground(work) (which uses ctx.waitUntil) is safe to call from a handler because the dedupe record already exists, but the sender has by then been told 200: if the background work fails, nothing retries it. Use it for best-effort follow-up (a cache purge), and for work that must happen persist a job row in the handler and process it separately.

How it meets the rest of the server

  • No identity. A webhook has no cookie and no bearer token. The session middleware only acts when a session cookie is present; a signed webhook without one passes through. Never use cookies to authenticate a webhook.
  • Rate limiting. Routes under /api/webhooks/ get a rule of their own, webhooks (1200 per minute per address, RATE_LIMIT_WEBHOOKS on Cloudflare), and are excluded from the per-address requests rule. A sender's few addresses carry the events of every shopper, so ordinary per-address limits would throttle legitimate events, while an unauthenticated flood is still bounded before the signature is even checked (each forged request costs a body read and an HMAC). If you pass your own rateLimit rules, give /api/webhooks/ the same treatment. Keep webhook files under that prefix.
  • CORS is irrelevant (the sender is not a browser) and harmless.
  • Method. Export only POST; the server answers 405 for the rest.
  • Not an RPC. The route is a plain file-based API route. The management manifest lists only /api/rpc/* as RPC methods, so webhooks never appear in it and have no request contract; the webhook_events collection is listed like any other.
  • Observability. Each request is a webhook <name> span with webhook.event_id, webhook.event_type and webhook.outcome (handled, duplicate, ignored, unauthorized, bad_payload, too_large, in_flight, handler_failed, store_error, not_configured). Logs name the route and event id; they never contain the secret or the body.

Adopting it

  • Add webhookEventCollection to appCollections; bun run codegen; commit the migration (bun run d1:generate on Cloudflare).
  • Add src/app/api/webhooks/<service>.ts as above.
  • Put the signing secret in the environment (.env locally, extra_secrets on Cloudflare, see Cloudflare).
  • Register https://<your public host>/api/webhooks/<service> with the sender. If it refuses your domain and accepts only its own hosted one (a CNAME to the platform in your Cloudflare zone), route just the webhook path on that hostname to the app instead: see Webhooks from another hostname.
  • Test with signWebhook, then with the sender's own test delivery.

Fourthwall

From Fourthwall's webhook documentation: the signature is the base64 HMAC-SHA-256 of the entire raw body, in X-Fourthwall-Hmac-SHA256 (X-Fourthwall-Hmac-Apps-SHA256 for platform apps), keyed with the secret shown in the shop's webhook settings; there is no timestamp. The event envelope has id (unique; "if you receive multiple events with the same id, treat them as duplicates"), type (ORDER_PLACED, ORDER_UPDATED, …), shopId, testMode, createdAt and data. Delivery is at-least-once, any answer other than 200 is retried (up to five attempts), ordering is not guaranteed (an ORDER_UPDATED can precede ORDER_PLACED, so key rows on the order id and make each handler an upsert), and some events may never arrive: reconcile periodically against Fourthwall's API for data that must be exact. Fourthwall's documentation lists no separate refund event; a refund arrives as an order update.

Anti-patterns

Avoid
Do instead
await req.json() (or any parsing) before verifyingVerify the raw bytes; createWebhookRoute hands you the parsed event afterwards
Re-serializing the parsed body to check the signatureSign/verify exactly the bytes received
Comparing signatures with ===crypto.subtle.verify (what the built-ins use)
An IP allowlist as the authenticationThe signature; sender addresses change and are shared
A secret read at module load (const secret = process.env.X)secret: () => process.env.X
Skipping the dedupe record because "the handler is idempotent"Keep the record and make the handler idempotent too
Acknowledging before the handler has runReturn after the work; fail with a throw
Throwing for an event you can never processLog and acknowledge it
Collection access rules to "authorize" a webhookA verified signature, then overrideAccess: true on exactly what the event may change
Putting the webhook outside /api/webhooks/Keep the prefix, so it gets its own rate-limit bucket