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.// src/collections/index.ts — once per app, like sessionCollection
import { webhookEventCollection } from "@dash/server";
export const appCollections = [/* ... */, webhookEventCollection];// 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 /* ... */ },
});
},
},
});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.Step | Outcome | Why this order |
|---|---|---|
| Read the body as bytes, at most maxBodyBytes (default 1 MiB) | 413 over the limit, without reading further | Bounds 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 configured | Misconfiguration must fail closed, never accept unsigned requests. |
| Verify the signature on those bytes | 401, empty body | Nothing 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 type | 400 | Only 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/handle | 200, nothing recorded | A sender must not retry forever for events the app ignores. |
| Claim the event id (below) | duplicate 200; in flight 409 | The handler never runs without a durable record. |
| Run the handler | throws → release the claim, 500 | A failed event must be retried, so it must not look done. |
| Mark the event done | 200 | If only this write fails the handler already succeeded: acknowledge anyway. |
200 as delivered: Fourthwall, for one, counts
any other status (and anything slower than about two seconds) as a failed delivery and
retries it.verify and secret(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-SHA256 | hmacSha256({ 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 window | timestampedHmacSha256({ 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 else | your 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.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.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.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.200, handler not run.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.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.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.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.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).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.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./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.POST; the server answers 405 for the rest./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.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.webhookEventCollection to appCollections; bun run codegen; commit the
migration (bun run d1:generate on Cloudflare).src/app/api/webhooks/<service>.ts as above..env locally, extra_secrets on Cloudflare,
see Cloudflare).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.signWebhook, then with the sender's own test delivery.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.Avoid | Do instead |
|---|---|
| await req.json() (or any parsing) before verifying | Verify the raw bytes; createWebhookRoute hands you the parsed event afterwards |
| Re-serializing the parsed body to check the signature | Sign/verify exactly the bytes received |
| Comparing signatures with === | crypto.subtle.verify (what the built-ins use) |
| An IP allowlist as the authentication | The 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 run | Return after the work; fail with a throw |
| Throwing for an event you can never process | Log and acknowledge it |
| Collection access rules to "authorize" a webhook | A 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 |