Webhooks Developer Guide

Technology: webhooks · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/webhooks

Insight:

A webhook is a reverse API call: the provider POSTs an event to a public URL you own, so the whole job is proving the request is genuine before you act on it. Verify the HMAC over the raw body (await req.text() in a Next.js Route Handler), ACK 2xx fast, then do the slow work on a queue. Delivery is at-least-once and unordered, so dedupe on the event or delivery id and re-fetch state instead of trusting event order. Watch the 2026 trap: svix 2.x Webhook.verify() returns undefined. It only throws on failure, so verify first and JSON.parse the raw body yourself (or use Clerk's verifyWebhook(), which returns the typed event). The odd one out for codeAmani is M-Pesa/Daraja: callbacks are unsigned and never retried, so allowlist Safaricom's 12 gateway IPs, dedupe on CheckoutRequestID, and always run a reconciliation job.

██╗    ██╗███████╗██████╗ ██╗  ██╗ ██████╗  ██████╗ ██╗  ██╗███████╗
██║    ██║██╔════╝██╔══██╗██║  ██║██╔═══██╗██╔═══██╗██║ ██╔╝██╔════╝
██║ █╗ ██║█████╗  ██████╔╝███████║██║   ██║██║   ██║█████╔╝ ███████╗
██║███╗██║██╔══╝  ██╔══██╗██╔══██║██║   ██║██║   ██║██╔═██╗ ╚════██║
╚███╔███╔╝███████╗██████╔╝██║  ██║╚██████╔╝╚██████╔╝██║  ██╗███████║
 ╚══╝╚══╝ ╚══════╝╚═════╝ ╚═╝  ╚═╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═╝╚══════╝

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:

  1. 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.
  2. 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.
  3. 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).

sequenceDiagram
    participant P as Provider
    participant E as Your endpoint
    participant Q as Queue/Worker
    P->>P: Event occurs · sign payload
    P->>E: POST /api/webhooks/provider · raw body + signature headers
    E->>E: Verify signature + timestamp
    E->>E: Claim event id (unique insert)
    E->>Q: Enqueue slow work
    E-->>P: 2xx ACK fast
    Q->>Q: Process out of band
    Note over P,E: No 2xx in time then retry with backoff

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:


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.

flowchart TD
    A["POST arrives"] --> B{"Signature valid?"}
    B -->|"no"| R1["Return 400 or 401 · reject"]
    B -->|"yes"| C{"Timestamp fresh?"}
    C -->|"no · too old"| R2["Return 400 · replay"]
    C -->|"yes"| D{"Event id seen before?"}
    D -->|"yes"| R3["Return 200 · dedupe no-op"]
    D -->|"no"| E["Insert id · enqueue work"]
    E --> F["Return 200 · ACK"]

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:

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 svix 2.x. Since 2.2.0 (2026-08-31), new Webhook(secret).verify(payload, headers) returns undefined. Its type is verify(...): undefined. It throws a WebhookVerificationError on a bad signature or a timestamp outside ±5 minutes, and that's all. Code written for 1.x (const evt = wh.verify(...)) now gets undefined and breaks. 2.0.0 and 2.1.0 still returned the payload and were yanked for that reason. Verify, then JSON.parse the 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 key

The 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;
}
flowchart TD
    A["Event id arrives"] --> B["INSERT (provider, id)"]
    B --> C{"Unique violation?"}
    C -->|"yes · duplicate"| D["Skip work · return 200"]
    C -->|"no · first time"| E["Enqueue work once"]
    E --> F["Return 200"]

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:


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 3000

Use 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


Security checklist


codeAmani notes

Official docs: