Webhooks Developer Guide
What is a webhook?
Verify the raw body, ACK in <1s, enqueue the slow work, dedupe on the event id.
The receiver pattern: verify HMAC-SHA256 over `id.timestamp.payload` against the RAW body with timingSafeEqual; reject stale timestamps (±5 min) to stop replays; INSERT the event id under a unique constraint to dedupe at-least-once delivery; return 2xx, then queue the work. Svix (and therefore Clerk) implement Standard Webhooks; Stripe's constructEvent is a close variant; GitHub signs the body as X-Hub-Signature-256. Watch out: svix 2.x Webhook.verify() returns undefined and only throws, so JSON.parse the raw body after it (or use Clerk's verifyWebhook(), which returns the event). For codeAmani: Daraja callbacks aren't signed or retried — allowlist Safaricom's gateway IPs, dedupe on CheckoutRequestID, ACK ResultCode 0 fast, and reconcile out of band.
Six things to get right
The rules that separate a safe receiver from a public mutation endpoint. Tap a card for the details.
Delivery simulator — does the receiver ACK, reject, or dedupe?
Send four kinds of delivery at a receiver and watch it run the three gates — verify the signature, check the timestamp, dedupe the event id — then decide its HTTP response. This is the whole webhook security model in one widget.
- ✓1 · Verify HMAC-SHA256 signaturematches signature over raw body
- ✓2 · Timestamp within ±5 min tolerancefresh, not a replay
- ✓3 · Event id not seen before (dedupe)first delivery — claim id, enqueue work
The receiver runs three gates in order — signature → freshness → dedupe. Only a bad signature or stale timestamp earns a 400; a duplicate is harmless, so it still returns 200 so the provider stops retrying.
██╗ ██╗███████╗██████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗███████╗
██║ ██║██╔════╝██╔══██╗██║ ██║██╔═══██╗██╔═══██╗██║ ██╔╝██╔════╝
██║ █╗ ██║█████╗ ██████╔╝███████║██║ ██║██║ ██║█████╔╝ ███████╗
██║███╗██║██╔══╝ ██╔══██╗██╔══██║██║ ██║██║ ██║██╔═██╗ ╚════██║
╚███╔███╔╝███████╗██████╔╝██║ ██║╚██████╔╝╚██████╔╝██║ ██╗███████║
╚══╝╚══╝ ╚══════╝╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝Webhooks Developer Guide
Focus: receive webhooks safely. Verify the signature over the raw body, ACK fast, then do the slow work on a queue. The same three moves work for Stripe, Clerk, GitHub, Shopify, Twilio, Meta/WhatsApp, Notion, Sentry, Figma and M-Pesa/Daraja.
Overview
A webhook is a reverse API call. Instead of polling a provider ("anything new yet?"), the provider POSTs a small event to a URL you own the moment something happens: a payment succeeded, a user signed up, an error spiked. It's the push half of an event-driven system, and the cheapest way to react in near-real-time.
Every receiver has to respect three hard truths:
- The internet is hostile. Your endpoint is public, so anyone can POST to it. You must cryptographically verify that each request came from the provider, usually with an HMAC-SHA256 signature over the raw body.
- Delivery is at-least-once and unordered. Providers retry on timeouts and non-2xx replies, so the same event can arrive twice, and events can arrive out of order. Be idempotent: dedupe on the event or delivery id.
- Slow receivers get retried, or disabled. Sentry wants a reply within 1 second, Shopify within 5, GitHub within 10. Verify, record, ACK, and push real work to a queue.
Most modern providers have converged on one wire format, now written down as the Standard Webhooks spec: the signed content is id.timestamp.payload, signed with HMAC-SHA256, base64-encoded and prefixed v1,. Svix is the reference implementation, and Clerk and Resend deliver through it. Stripe uses a close variant. GitHub, Meta and Notion sign the bare body as sha256=<hex>. Learn one and you can read them all.
Current versions (npm, 2026-10-20)
| Package | Version | What it's for | Notes |
|---|---|---|---|
stripe | 23.0.0 | stripe.webhooks.constructEvent() / constructEventAsync() | Ships API version 2026-09-30.endive. Node ≥ 20. Tolerance 0 now disables the timestamp check |
svix | 2.8.0 | new Webhook(secret).verify() for any Svix sender | verify() returns undefined since 2.2.0. ESM-only (CommonJS dropped in 2.0). engines.node >= 22 |
standardwebhooks | 1.1.1 | Provider-neutral Standard Webhooks verify | verify() still returns the parsed JSON (pass { jsonParse: false } to skip) |
@octokit/webhooks-methods | 6.0.0 | GitHub verify(secret, body, signature) | ESM-only, Node ≥ 20. Also verifyWithFallback() for secret rotation |
@clerk/nextjs | 7.9.17 | verifyWebhook(req) from @clerk/nextjs/webhooks | Built on standardwebhooks; returns the typed WebhookEvent |
resend | 6.34.1 | resend.webhooks.verify({ payload, headers, webhookSecret }) | Returns the parsed payload |
twilio | 6.2.0 | validateRequest() / validateRequestWithBody() | HMAC-SHA1 over URL + params |
@notionhq/client | 5.27.1 | verifyWebhookSignature() | Helper added in 5.23.0 |
next | 16.4.2 | Route Handlers (app/**/route.ts) | Raw body via await request.text() |
Official Documentation
| Source | URL | What it covers |
|---|---|---|
| Standard Webhooks spec | https://www.standardwebhooks.com/ | Headers, v1 / v1a schemes, secret format, retry schedule |
| Svix: verifying payloads | https://docs.svix.com/receiving/verifying-payloads/how | Webhook.verify(), header names |
| Svix: retry schedule | https://docs.svix.com/retries | Retry delays, endpoint disabling |
| Stripe webhooks | https://docs.stripe.com/webhooks | Delivery, retries, duplicates, ordering, Stripe-Signature |
| Clerk: syncing via webhooks | https://clerk.com/docs/guides/development/webhooks/syncing | verifyWebhook(), at-least-once semantics |
| GitHub: validating deliveries | https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries | X-Hub-Signature-256 |
| GitHub: failed deliveries | https://docs.github.com/en/webhooks/using-webhooks/handling-failed-webhook-deliveries | No automatic redelivery, 10 s timeout |
| Shopify: verify deliveries | https://shopify.dev/docs/apps/build/webhooks/verify-deliveries | X-Shopify-Hmac-SHA256, retries, dedupe headers |
| Twilio: webhook security | https://www.twilio.com/docs/usage/webhooks/webhooks-security | X-Twilio-Signature, bodySHA256 |
| Meta: webhooks getting started | https://developers.facebook.com/docs/graph-api/webhooks/getting-started | hub.challenge, X-Hub-Signature-256 |
| Notion webhooks | https://developers.notion.com/reference/webhooks | verification_token, X-Notion-Signature |
| Sentry integration webhooks | https://docs.sentry.io/integrations/integration-platform/webhooks/ | Sentry-Hook-Signature, 1 s timeout |
| Figma webhooks v2 | https://developers.figma.com/docs/rest-api/webhooks-security/ | passcode check, retries |
| Resend: verify requests | https://resend.com/docs/webhooks/verify-webhooks-requests | resend.webhooks.verify() |
| Next.js Route Handlers | https://nextjs.org/docs/app/api-reference/file-conventions/route | Raw body, segment config |
Anatomy of a delivery
An event happens at the provider. It serialises a JSON payload, signs it with your shared secret, and POSTs the payload plus signature headers to your URL. Your endpoint verifies, records and replies 2xx, and the provider marks the delivery acknowledged. Any other reply, or a timeout, schedules a retry (for providers that retry at all).
Under the Standard Webhooks / Svix scheme the headers carry everything verification needs:
| Header | Meaning |
|---|---|
webhook-id / svix-id | Unique message id: your idempotency key (the same on every retry) |
webhook-timestamp / svix-timestamp | Unix seconds when sent: used for replay protection |
webhook-signature / svix-signature | Space-separated v1,<base64> values (several during secret rotation) |
Stripe folds all three into one Stripe-Signature header (t=<ts>,v1=<hex>). GitHub sends X-Hub-Signature-256: sha256=<hex> plus a separate X-GitHub-Delivery id. Same idea, different packaging. The full matrix is in reference/signature-schemes-cheatsheet.md.
Raw bodies in Next.js 16 Route Handlers
Every signature is computed over the exact bytes the provider sent. Next.js App Router Route Handlers get a Web Request, and there's no body-parser to switch off:
- Read once with
await req.text()(orawait req.arrayBuffer()for binary-safe handling). Verify against that string, thenJSON.parsethe same string. - Never call
req.json()first. Parsing and re-serialising changes whitespace and key order, and the HMAC fails. - A body can only be read once. If you need it twice, read the text once and pass the string around (or
req.clone()before reading). - Keep webhook routes on the Node.js runtime (the default;
export const runtime = "nodejs"makes it explicit). On edge or Workers runtimes, use the async verifiers (constructEventAsync, Web Crypto). proxy.ts(Next.js 16's renamedmiddleware.ts) must not read or rewrite the body of webhook routes, and must not put auth in front of them. Webhooks carry no user session. Exclude/api/webhooks/from auth matchers, and keep Vercel Deployment Protection off for preview URLs you register with a provider.- POST Route Handlers are never cached, so no
dynamicexport is needed.
The receiver pattern: verify → claim → ACK → enqueue
The single most important architectural decision: don't do real work inside the request. Verify, write a dedupe row, return 2xx, and hand the heavy lifting (DB writes, emails, fulfilment, AI calls) to a background queue. That keeps you under every provider's timeout, and a slow downstream service can't cause a retry storm.
A duplicate still returns 200: you already did the work, so acknowledge it and move on. Only a bad signature or stale timestamp earns a 4xx. If your own dedupe insert or enqueue fails, return 5xx so the provider retries.
Need a quick fire-and-forget step on Vercel without a queue? after() from next/server runs a callback after the response is sent. It isn't durable: if the function dies, the work is lost. Use it for logging or cache warm-ups, not for money.
Signature verification
An unverified webhook endpoint is a public, unauthenticated POST handler that can change your database. Three rules:
- Verify against the RAW body. See the section above.
- Compare in constant time (
crypto.timingSafeEqualafter a length check), never with===. - Keep the secret server-side. It's as sensitive as a password. One secret per endpoint.
Clerk: verifyWebhook() (preferred)
Clerk delivers through Svix. In Next.js, verifyWebhook(req) from @clerk/nextjs/webhooks reads CLERK_WEBHOOK_SIGNING_SECRET, checks the three svix-* headers and the 5-minute tolerance, and returns the typed event. Outside Next.js, use the same function from @clerk/backend/webhooks. See ../clerk/CLAUDE_CODE_INTEGRATION.md and examples/clerk-route.ts.
// app/api/webhooks/clerk/route.ts
import { verifyWebhook } from "@clerk/nextjs/webhooks";
import type { NextRequest } from "next/server";
export async function POST(req: NextRequest): Promise<Response> {
let evt: Awaited<ReturnType<typeof verifyWebhook>>;
try {
evt = await verifyWebhook(req); // throws on a bad signature or stale timestamp
} catch {
return new Response("invalid signature", { status: 400 });
}
const deliveryId = req.headers.get("svix-id") ?? ""; // idempotency key
if (evt.type === "user.created") {
await enqueue(deliveryId, evt.type, evt.data.id);
}
return new Response(null, { status: 200 });
}Raw Svix / Standard Webhooks (any Svix sender, non-Next runtimes)
Breaking change in
svix2.x. Since 2.2.0 (2026-08-31),new Webhook(secret).verify(payload, headers)returnsundefined. Its type isverify(...): undefined. It throws aWebhookVerificationErroron a bad signature or a timestamp outside ±5 minutes, and that's all. Code written for 1.x (const evt = wh.verify(...)) now getsundefinedand breaks. 2.0.0 and 2.1.0 still returned the payload and were yanked for that reason. Verify, thenJSON.parsethe same raw string.
import { Webhook } from "svix"; // svix@2.8.0: ESM-only, Node >= 22
const SECRET = process.env.CLERK_WEBHOOK_SIGNING_SECRET!; // "whsec_..."
export async function POST(req: Request): Promise<Response> {
const payload = await req.text(); // RAW body
const headers = {
"svix-id": req.headers.get("svix-id") ?? "",
"svix-timestamp": req.headers.get("svix-timestamp") ?? "",
"svix-signature": req.headers.get("svix-signature") ?? "",
};
try {
new Webhook(SECRET).verify(payload, headers); // returns undefined; throws on failure
} catch {
return new Response("invalid signature", { status: 400 });
}
const evt = JSON.parse(payload) as { type: string; data: unknown }; // trusted now
await enqueue(headers["svix-id"], evt.type, evt.data);
return new Response("ok", { status: 200 });
}The provider-neutral standardwebhooks package (1.1.1) works the same way with webhook-* headers, but its verify() still returns the parsed JSON. Don't mix up the two libraries' return values. Resend wraps it as resend.webhooks.verify({ payload, headers: { id, timestamp, signature }, webhookSecret }), which also returns the parsed payload.
Stripe: constructEvent
Stripe verifies and parses in one call. Pass the raw body string or Buffer, the Stripe-Signature header and the endpoint's own whsec_... secret. The SDKs default to a 5-minute tolerance (DEFAULT_TOLERANCE = 300). In stripe@23, passing tolerance 0 skips the timestamp check, so don't. Ignore every scheme except v1; test events also carry a fake v0 signature.
// app/api/webhooks/stripe/route.ts (full version with dedupe: examples/route.ts)
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { apiVersion: "2026-09-30.endive" });
const ENDPOINT_SECRET = process.env.STRIPE_WEBHOOK_SECRET!; // "whsec_..."
export async function POST(req: Request): Promise<Response> {
const body = await req.text(); // raw
const sig = req.headers.get("stripe-signature") ?? "";
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(body, sig, ENDPOINT_SECRET);
// Edge / Workers runtime: event = await stripe.webhooks.constructEventAsync(body, sig, ENDPOINT_SECRET);
} catch (err) {
return new Response(`Webhook Error: ${(err as Error).message}`, { status: 400 });
}
await enqueue(event.id, event.type, event); // event.id is the dedupe key
return new Response("ok", { status: 200 });
}Event destinations that send thin events (API v2) are parsed with stripe.parseEventNotification(body, sig, secret) instead. That's the same signature check, and it returns a lightweight notification you then fetch. See ../stripe/CLAUDE_CODE_INTEGRATION.md.
GitHub: @octokit/webhooks-methods
GitHub signs only the raw body (no id or timestamp), as hex, prefixed sha256=, in X-Hub-Signature-256. Handle the payload as UTF-8. Ignore the legacy SHA-1 X-Hub-Signature header.
import { verify } from "@octokit/webhooks-methods"; // 6.0.0
const ok = await verify(process.env.GITHUB_WEBHOOK_SECRET!, rawBody, signatureHeader); // constant-time
const deliveryId = req.headers.get("x-github-delivery"); // dedupe keyThe full handler is in examples/github-route.ts. To do it without a dependency, verifySha256Prefixed() in examples/verify-webhook.ts is the same HMAC with timingSafeEqual.
Raw HMAC (the primitive underneath)
When a provider has no SDK, verify the HMAC yourself. The key moves are: HMAC the raw body, encode the way the provider does (hex or base64), then timingSafeEqual after a length check.
import { createHmac, timingSafeEqual } from "node:crypto";
/** Standard Webhooks v1: `${id}.${timestamp}.${body}`, base64, `v1,` prefix, ±5 min. */
export function verifyStandard(opts: {
rawBody: string;
id: string;
timestamp: string;
signatureHeader: string; // "v1,abc= v1,def=" (several during rotation)
secret: string; // "whsec_<base64>"
}): boolean {
const ts = Number(opts.timestamp);
if (!Number.isInteger(ts) || Math.abs(Date.now() / 1000 - ts) > 300) return false;
const key = Buffer.from(opts.secret.replace(/^whsec_/, ""), "base64");
const expected = Buffer.from(
createHmac("sha256", key).update(`${opts.id}.${opts.timestamp}.${opts.rawBody}`).digest("base64"),
);
return opts.signatureHeader.split(" ").some((entry) => {
const [version, sig] = entry.split(",");
if (version !== "v1" || !sig) return false;
const given = Buffer.from(sig);
return given.length === expected.length && timingSafeEqual(given, expected);
});
}Other providers at a glance
| Provider | Header | How to verify | Dedupe on |
|---|---|---|---|
| Shopify | X-Shopify-Hmac-SHA256 | base64 HMAC-SHA256 of the raw body, keyed with the app client secret | X-Shopify-Webhook-Id (X-Shopify-Event-Id correlates fan-out) |
| Twilio | X-Twilio-Signature | HMAC-SHA1 (base64) of the full URL + alphabetically sorted POST params, keyed with the auth token. Use twilio.validateRequest(); for JSON bodies use validateRequestWithBody() (checks the bodySHA256 query param). Use the exact public URL Twilio called | MessageSid / CallSid |
| Meta / WhatsApp Cloud API | X-Hub-Signature-256 | sha256= + hex HMAC-SHA256 of the raw body, keyed with the App Secret. Subscription check: answer the GET with hub.challenge when hub.verify_token matches | message id |
| Notion | X-Notion-Signature | sha256= + hex HMAC-SHA256 of the raw body, keyed with the one-time verification_token. Or verifyWebhookSignature() from @notionhq/client ≥ 5.23.0 | event id |
| Sentry (integration platform) | Sentry-Hook-Signature | hex HMAC-SHA256, keyed with the integration Client Secret. Reply within 1 s | Request-ID |
| Figma (webhooks v2) | none | Compare the passcode field in the payload with the one you set at creation. A wrong passcode gets a 400 webhook_id + timestamp (no delivery id is documented) | |
| Resend | svix-* | resend.webhooks.verify() (Standard Webhooks) | svix-id |
| M-Pesa / Daraja | none | Unsigned. Allowlist Safaricom's gateway IPs, then match CheckoutRequestID to a pending record | CheckoutRequestID |
Idempotency: dedupe on the event id
Because delivery is at-least-once, processing the same event twice must have the same effect as processing it once. The cleanest way is a unique constraint on (provider, event_id): let the database reject the duplicate.
import { createClient } from "@supabase/supabase-js";
const db = createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_SERVICE_ROLE_KEY!);
/** Returns true the FIRST time we see this id. */
export async function claimEvent(provider: string, eventId: string, type: string): Promise<boolean> {
const { error } = await db
.from("webhook_events") // primary key (provider, event_id)
.insert({ provider, event_id: eventId, type, received_at: new Date().toISOString() });
if (error?.code === "23505") return false; // unique_violation: already handled
if (error) throw error; // 5xx -> provider retries
return true;
}Which id to use:
| Provider | Idempotency key |
|---|---|
| Stripe | event.id (evt_...); unchanged across retries |
| Svix senders (Clerk, Resend) | svix-id header |
| Standard Webhooks | webhook-id header |
| GitHub | X-GitHub-Delivery (a redelivery keeps the same GUID) |
| Shopify | X-Shopify-Webhook-Id |
| Daraja STK | CheckoutRequestID (stored when the STK Push is accepted) |
Without a database constraint, fall back to Redis SET key NX EX 604800, keyed on the id. Keep keys at least as long as the provider's retry window (Stripe retries for up to 3 days). Either way, the id is the dedupe key, not the payload contents. The worker should be idempotent too: upsert by entity id, and use provider idempotency keys on any outgoing API calls.
Retries & at-least-once delivery
Providers retry when you don't return 2xx in time. The schedule tells you how long duplicates can keep arriving and when you need reconciliation:
| Provider | Timeout | Retry behaviour (official docs, 2026-10-20) |
|---|---|---|
| Stripe | "Quickly return a 2xx" (no number published) | Live: up to 3 days, exponential backoff. Sandbox: 3 retries over a few hours |
| Svix (Clerk, Resend) | 30 s | Immediately, 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 10 h (about 27.5 h in all). An endpoint failing for 5 days is disabled |
| Standard Webhooks spec | 15–30 s recommended | Example schedule spans about 3 days with jitter |
| GitHub | 10 s | No automatic redelivery. Redeliver manually or through the REST API |
| Shopify | 1 s connect, 5 s total | 8 retries over 4 hours. After 8 consecutive failures, Admin-API subscriptions are deleted |
| Meta / WhatsApp | not stated | Retries immediately, then with decreasing frequency for 36 hours |
| Figma | not stated | 3 retries: 5 min, 30 min, 3 h |
| Sentry | 1 s | Not documented (see NOTES.md) |
| M-Pesa / Daraja | keep it under ~1 s | No retries. Missed callbacks are discarded. Reconcile with STK Query / Transaction Status |
What this means: return 2xx only after you've durably accepted the event (dedupe row written, job queued). If your worker fails after the ACK, the provider won't retry, so your queue's own retry has to cover it. For no-retry providers (GitHub, Daraja), run a reconciliation job that lists recent deliveries or queries status.
Replay-attack protection
A captured and replayed request still has a valid signature, so the signature alone can't stop it. The defence is the timestamp: reject anything outside a window (±5 minutes is the convention). Stripe, Svix, standardwebhooks and Clerk enforce this for you. In raw HMAC code you do it yourself.
GitHub, Meta, Shopify, Notion and Sentry don't put a timestamp inside the signature, so a replay passes verification. Idempotency is the replay defence for those: a replayed delivery id is already in your table.
Ordering caveats
Webhooks are not ordered. customer.subscription.updated can arrive before ...created. A Clerk user.updated can land before user.created. A Daraja callback can beat your own write of the STK Push response. Defences:
- Make handlers commutative: upsert by entity id, never blind-insert.
- For state machines, re-fetch the current object from the provider's API in the worker, instead of trusting the event snapshot (Stripe's own advice).
- Use a version or timestamp to drop stale updates: Stripe
event.created, Clerkdata.updated_at. Don't let a lateupdatedresurrect a deleted row.
Local testing
Callbacks must reach a public HTTPS URL, so localhost:3000 alone won't work.
# Provider CLIs forward straight to localhost (no tunnel; events are signed for you)
stripe listen --forward-to localhost:3000/api/webhooks/stripe # prints a session-only whsec_...
stripe trigger payment_intent.succeeded
gh webhook forward --repo owner/repo --events=push --url=http://localhost:3000/api/webhooks/github
clerk webhooks listen # Clerk CLI relay tunnel
# Anything else: tunnel localhost to a public HTTPS URL
ngrok http 3000Use the whsec_... that stripe listen prints in .env.local, not the Dashboard endpoint's secret. For Daraja, Safaricom says public tunnels are "usually blocked". If sandbox callbacks don't arrive through ngrok, use a deployed preview URL with Deployment Protection off for that path (see ../daraja api/CLAUDE_CODE_INTEGRATION.md).
To unit-test handlers without a network, sign your own payloads: stripe.webhooks.generateTestHeaderString({ payload, secret }), new Webhook(secret).sign(id, date, payload) (svix / standardwebhooks), and sign(secret, payload) from @octokit/webhooks-methods.
Secrets
Real secrets only (placeholders shown). Store them in the vault or .env.local, and in Vercel environment variables for deployed apps:
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
CLERK_WEBHOOK_SIGNING_SECRET=whsec_...
GITHUB_WEBHOOK_SECRET=your-random-secret
RESEND_WEBHOOK_SECRET=whsec_...Provider-specific keys (Shopify client secret, Twilio auth token, Meta App Secret, Notion verification_token, Sentry client secret, Figma passcode) follow the same rule: server-side only, one per endpoint, never NEXT_PUBLIC_*.
| Setting (not a secret) | Example | Notes |
|---|---|---|
| Webhook route | /api/webhooks/<provider> | One route and one secret per provider |
| Daraja callback route | /api/payments/stk/callback | No mpesa/safaricom in the URL (Safaricom URL rules) |
| Timestamp tolerance | 300 s | SDK default; don't widen without a reason |
Observability & debugging
- Log the delivery id, event type and outcome for every request: that's your audit trail and dedupe evidence. Never log secrets or full payloads that contain personal data.
- Most dashboards (Stripe, Svix/Clerk, GitHub, Shopify) show each delivery's request and response, with a Resend/Redeliver button. Start debugging there.
- A flood of retries almost always means one of three things: you returned non-2xx, you timed out (work done inline), or something rewrote the raw body before verification.
400on every delivery means the wrong secret (Stripe CLI vs Dashboard, test vs live), verification against a parsed body, or, onsvix2.x, code that treatsverify()'sundefinedreturn as the event.- Optionally allowlist sender IPs as defence in depth: Stripe (https://docs.stripe.com/ips), Svix (https://docs.svix.com/webhook-ips.json). IP allowlisting is mandatory only for Daraja.
Security checklist
- Verify the signature on every request before trusting any field.
- Verify against the raw body (
req.text()), neverreq.json()first. - Use
timingSafeEqual(or the SDK), never===. - Enforce a timestamp tolerance (±5 min) where the scheme signs one. Never pass Stripe tolerance
0. - On
svix2.x, don't useverify()'s return value.JSON.parsethe raw body after it returns. - Be idempotent: a unique constraint on
(provider, event_id). - ACK fast (under 1 s for Sentry and Daraja; seconds for the rest), and push slow work to a queue.
- Return
5xxif your persistence fails, so retrying providers try again. - Keep webhook routes out of auth middleware (
proxy.ts) and out of Vercel Deployment Protection. - Keep signing secrets server-side, one per endpoint, never in client code or git. Rotate on leak (Svix/Standard Webhooks send several
v1,signatures during rotation). - HTTPS only.
codeAmani notes
- Secrets server-side only.
STRIPE_WEBHOOK_SECRET,CLERK_WEBHOOK_SIGNING_SECRET,GITHUB_WEBHOOK_SECRETand the M-Pesa consumer credentials live in the vault (Hazina) or.env.local, and in Vercel env vars in production. NeverNEXT_PUBLIC_*. They never touch the browser bundle. - Stripe is the default payment webhook for US-first projects:
app/api/webhooks/stripe/route.ts, verified withconstructEvent, deduped onevent.id. - Clerk means Svix. Use
verifyWebhook()from@clerk/nextjs/webhooks(it returns the typed event). If you drop to rawsvix, remember that 2.xverify()returnsundefined. - AI work goes on the queue. If a webhook triggers a Claude call (AI routing policy: Anthropic for reasoning), enqueue it. Never call a model inside the request; it blows every provider's timeout.
- M-Pesa / Daraja callbacks are the special case (Kenya-targeted projects only). Daraja does not sign callbacks and does not retry them. Instead:
- Allowlist Safaricom's 12 gateway IPs (listed in
../daraja api/CLAUDE_CODE_INTEGRATION.md, § Callback security & URL rules) at the edge or in the route. - Dedupe on
CheckoutRequestID. Store it the moment the STK Push is accepted, ignore callbacks for ids you didn't create, and finalize idempotently. - ACK in under 1 s with
{ "ResultCode": 0, "ResultDesc": "Accepted" }, then reconcile out of band. Run an STK Query / Transaction Status job for every payment stillpendingafter about 2 minutes. - Route naming: Safaricom bans
mpesa,safaricom,exec,cmd,sqlandqueryin callback URLs. Useapp/api/payments/stk/callback/route.ts, notapp/api/mpesa/...(the workspaceCLAUDE.mdtree is out of date on this). Code modules can keeplib/mpesa-*.tsnames. - Sandbox shortcode
174379, test phone254708374149.
- Allowlist Safaricom's 12 gateway IPs (listed in
- Route layout:
app/api/webhooks/<provider>/route.tsfor Stripe, Clerk, GitHub, Sentry, Resend and the rest.app/api/payments/...for Daraja.