Verifying Clerk Webhooks in Cloudflare Workers (Zero Dependencies)
How Clerk signs webhooks using Svix headers (svix-id, svix-timestamp, svix-signature), how to verify them with native Web Crypto in Cloudflare Workers, and how to test locally.
Clerk webhooks let you sync user.created, user.updated, and session.created events into your database as soon as users sign up. Under the hood, Clerk delivers webhooks using Svix, which signs every HTTP request with three custom headers: svix-id, svix-timestamp, and svix-signature.
If you verify Clerk webhooks inside a Cloudflare Worker, you do not need to bundle a large Node compatibility shim or third-party verification package. Everything required to validate Svix signatures is built directly into the Web Crypto API (crypto.subtle) available in every Cloudflare Worker.
How Clerk / Svix Webhook Signing Works
Every webhook request from Clerk includes these three headers:
svix-id: Unique message identifier (for example,msg_2x...), useful for idempotency checks.svix-timestamp: Unix timestamp in seconds when the delivery attempt was signed.svix-signature: Space-separated list of versioned base64 signatures, such asv1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=. Multiplev1,...entries can appear during secret rotation.
Your Clerk webhook signing secret looks like whsec_<base64_key>. To verify a request accurately:
- Reject requests missing
svix-id,svix-timestamp, orsvix-signature. - Validate that
svix-timestampis recent (typically within ±300 seconds / 5 minutes of the current server time) to prevent replay attacks. - Strip the
whsec_prefix from your signing secret and base64-decode the remainder into raw HMAC key bytes. - Build the signed payload string using the exact concatenation format:
${svix_id}.${svix_timestamp}.${raw_body} - Compute the HMAC-SHA256 digest of that string using the decoded secret bytes and base64-encode the resulting MAC.
- Compare your computed base64 signature against every
v1,<sig>entry insvix-signatureusing a constant-time comparison.
Zero-Dependency Cloudflare Worker Implementation
Below is a complete, production-ready Cloudflare Worker module using only standard crypto.subtle Web APIs—zero npm dependencies required:
export interface Env {
CLERK_WEBHOOK_SECRET: string; // e.g. "whsec_..."
}
const TIMESTAMP_TOLERANCE_SECONDS = 300; // 5 minutes
function base64ToUint8Array(base64: string): Uint8Array {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
function uint8ArrayToBase64(bytes: Uint8Array): string {
let binary = "";
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
function timingSafeEqualString(a: string, b: string): boolean {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) {
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
}
return diff === 0;
}
export async function verifyClerkWebhook(
request: Request,
signingSecret: string
): Promise<{ valid: boolean; rawBody: string; svixId?: string; reason?: string }> {
const svixId = request.headers.get("svix-id");
const svixTimestamp = request.headers.get("svix-timestamp");
const svixSignature = request.headers.get("svix-signature");
if (!svixId || !svixTimestamp || !svixSignature) {
return { valid: false, rawBody: "", reason: "Missing Svix headers" };
}
const timestampSec = Number(svixTimestamp);
if (!Number.isFinite(timestampSec)) {
return { valid: false, rawBody: "", reason: "Invalid svix-timestamp" };
}
const nowSec = Math.floor(Date.now() / 1000);
if (Math.abs(nowSec - timestampSec) > TIMESTAMP_TOLERANCE_SECONDS) {
return { valid: false, rawBody: "", reason: "Timestamp outside tolerance window" };
}
// Always read the exact raw body before JSON.parse()
const rawBody = await request.text();
const signedContent = `${svixId}.${svixTimestamp}.${rawBody}`;
const secretBase64 = signingSecret.startsWith("whsec_")
? signingSecret.slice("whsec_".length)
: signingSecret;
const keyBytes = base64ToUint8Array(secretBase64);
const cryptoKey = await crypto.subtle.importKey(
"raw",
keyBytes,
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"]
);
const macBuffer = await crypto.subtle.sign(
"HMAC",
cryptoKey,
new TextEncoder().encode(signedContent)
);
const expectedSignature = uint8ArrayToBase64(new Uint8Array(macBuffer));
// svix-signature can contain multiple space-separated entries during key rotation
const candidateSignatures = svixSignature.split(" ");
const matched = candidateSignatures.some((entry) => {
const [version, sig] = entry.split(",");
if (version !== "v1" || !sig) return false;
return timingSafeEqualString(sig, expectedSignature);
});
if (!matched) {
return { valid: false, rawBody, reason: "Signature mismatch" };
}
return { valid: true, rawBody, svixId };
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
if (request.method !== "POST") {
return new Response("Method Not Allowed", { status: 405 });
}
const result = await verifyClerkWebhook(request, env.CLERK_WEBHOOK_SECRET);
if (!result.valid) {
return Response.json({ error: result.reason }, { status: 400 });
}
const event = JSON.parse(result.rawBody) as { type: string; data: unknown };
// Deduplicate using result.svixId before updating your database (e.g. D1)
console.log("Verified Clerk event:", result.svixId, event.type);
return Response.json({ ok: true }, { status: 200 });
},
};
Common Pitfalls in Cloudflare Workers
- Mutating the body before hashing: Reading
await request.json()and re-stringifying it breakssvix-signatureverification because key spacing, Unicode escaping, or key ordering changes. Always verifyawait request.text()before parsing JSON. - Ignoring multiple signatures: Splitting
svix-signatureby space and checking everyv1,<sig>entry ensures zero downtime when you rotate secrets in the Clerk Dashboard. During rotation, Clerk/Svix includes both the old and new signatures in the same header. - Skipping the timestamp tolerance check: Without checking
svix-timestamp, an attacker who intercepts a signed request could replay that exact payload hours or days later. Enforcing a 300-second window keeps old requests invalid without breaking normal clock skew. - Missing idempotency on
svix-id: Retries reuse the samesvix-id. Store processedsvix-idvalues in Cloudflare D1 or KV with a unique constraint so duplicate deliveries remain harmless.
Why Edge Verification Matters for Clerk Events
Clerk events frequently drive onboarding flows: creating a user row in D1 or Postgres, provisioning a default organization workspace, or assigning initial billing metadata. If your webhook endpoint lives behind a slow serverless cold start or fails on malformed body parsing, Clerk’s delivery retries stack up and newly registered users hit broken “account not found” states right after signing in. Running signature verification directly inside a Cloudflare Worker removes cold-start overhead and lets you accept and persist the raw event in milliseconds before running heavier downstream syncs.
Inspecting and Replaying Clerk Webhooks with EdgeHook
Before writing database sync logic, it helps to see the exact user.created or organizationMembership.created payload Clerk sends—along with its svix-id, svix-timestamp, and svix-signature headers.
You can do this today using EdgeHook’s Day-1 live tools:
- Generate a 24h sandbox URL: Open EdgeHook to get an instant
/in/:idendpoint running on Cloudflare Workers (no account needed; stores events up to 256 KB for 24 hours). - Send a Clerk test event: Paste your
/in/:idURL into the Clerk Dashboard’s Webhooks -> Testing tab and triggeruser.created. Inspect the Svix headers and JSON payload directly in your browser. - Pull and replay against
wrangler dev:
# Pull captured Clerk webhooks from your 24h EdgeHook sandbox
npx edgehook-cli pull <sandbox-url-or-id> --save ./.edgehook/clerk
# Replay to your local Cloudflare Worker (`wrangler dev`)
npx edgehook-cli replay ./.edgehook/clerk --to http://127.0.0.1:8787/webhooks/clerk
(Note: Because verifyClerkWebhook enforces a 5-minute tolerance on svix-timestamp, replaying older saved payloads will trip the timestamp check unless you temporarily widen TIMESTAMP_TOLERANCE_SECONDS in local dev or re-sign test fixtures. You can also capture live local traffic by running npx edgehook-cli listen --port 4000 --forward http://127.0.0.1:8787/webhooks/clerk --save ./.edgehook/clerk to inspect headers and save events to disk as they arrive.)
Live Today vs. On the Roadmap
Here is what is live in EdgeHook today versus what is planned next:
- Live today (Day 1): Unauthenticated 24-hour webhook sandbox (
/in/:idcapture and/api/sandbox/:id/eventsinspection), the zero-dependencyedgehook-cli(listen,replay,pull,send), waitlist signup, and Founding Member pre-order access via Polar when configured. - On the roadmap (not yet live): Hosted multi-tenant edge proxy endpoints, managed edge signature verification (including Svix/Clerk, Stripe, and Shopify), automatic exponential retries, 1-click hosted dashboard replay, Slack/Discord alerts, and paid retention tiers (Indie $29/mo for 14-day retention, Pro $49/mo for 30-day retention).
Next Steps
- Capture a live Clerk webhook right now: Open the 24h sandbox at EdgeHook.
- Want managed Svix verification and edge retries? Join the waitlist at /#waitlist.
- View the CLI source: Check out
edgehook-cliat /.
Debug your webhooks in seconds
Inspect real Stripe, Shopify, or Clerk payloads in our free 24-hour Cloudflare Workers sandbox (live today), or join the waitlist for managed retries and replay.