Securing Webhooks with Cloudflare Workers: A Didit Guide
Verify Didit webhooks inside a Cloudflare Worker: check X-Timestamp within 300 seconds, compare HMAC-SHA256 on the raw body, verify the -Previous header with the replaced secret during rotation, then act once per event id.

Contents
In this guide
Jump to the part you need.
This guide is for developers who receive Didit verification events inside a Cloudflare Worker and want every request checked before it changes state. You need one destination signing secret and one Worker route. The checks behind those events are priced per completed check, for example $0.33 for a full ID check. The caveat: the signature covers the bytes of the body, so nothing may parse or re-encode the request before you hash it.
Last updated: November 26, 2026. Prices checked against the live Didit price feed on November 26, 2026.
| Item | What to use |
|---|---|
| Endpoint | A POST route on your Worker, for example https://didit-webhook-handler.your-subdomain.workers.dev |
| Headers to verify | X-Timestamp plus X-Signature in this sample. X-Signature-V2 is the reference-recommended alternative when your stack can rebuild the canonical JSON. |
| Freshness window | 300 seconds between now and X-Timestamp |
| Algorithm | HMAC-SHA256 with the destination signing secret |
| Rotation | For 24 hours after a secret rotation, the current headers use the new secret and the -Previous headers use the replaced secret. Bind them separately. |
| Events | Exact names in subscribed_events, with no wildcard |
| Reply | 2xx after signature, timestamp and JSON parse pass. One idempotent state change per event_id is your code's job. |
| Price of the checks behind the events | Full ID check $0.33 per completed check, AML screening $0.20, KYB from $2.00 per company |
Start free in the sandbox at business.didit.me, no sales call. If you also want an AI assistant to read the same data, connect Didit through our MCP server. Every check price is on didit.me/pricing, and the webhook reference is docs.didit.me/integration/webhooks.
The outcome, and the method we recommend
The outcome is a Worker route that answers Didit with 2xx only after three gates pass: the timestamp is inside 300 seconds, the HMAC-SHA256 signature matches the destination secret, and the body parses as the event you expected. Everything else gets a 4xx and no state change.
This guide verifies X-Signature over the exact raw body. The reference recommends X-Signature-V2 when your stack can rebuild the sorted, Unicode-preserved canonical JSON, and that is the better choice when middleware normalizes JSON. The sample below implements neither X-Signature-V2 nor that canonicalization, so do not read it as supporting that header. In a Worker, X-Signature is the one we can show end to end because request.text() hands you the same bytes the signature was computed over, provided you read it before any parser touches the request. Use one path, not a half-built second one.
Do not build on X-Signature-Simple. It authenticates the envelope only, not the decision body, and the reference lists it as a deprecated last-resort fallback. If you verify with it, re-fetch the decision from GET /v3/session/{session_id}/decision/ instead of trusting the payload.
Didit serves 4,000+ companies, covering session status changes, entity changes, transaction events and Investigator activity. The mechanics live in the webhook reference; this page is the Worker-shaped version of it.
Prerequisites
- A Didit application and its API key, created under Developers then API keys in the Business Console. Keep the key server-side.
- A webhook destination with its own signing secret. Use a destination, not the legacy per-application
webhook_url. - A Cloudflare account with Wrangler runnable through
npx. - The event families you want in
subscribed_events. There is no wildcard, so anything you leave out never arrives. - A sandbox application for testing. The sandbox is free on every plan and nothing is charged there.
Step by step
Create the destination and copy its secret. In the Business Console create a webhook destination for the application, then open it to read the signing secret. The list endpoint returns only
secret_last4, so the full secret comes from the single-destination callGET /v3/webhook/destinations/{destination_uuid}/. A destination also gives you the rotation window described below, which the legacywebhook_urlnever receives.Subscribe to the events you need.
subscribed_eventstakes exact names such asstatus.updated,data.updated,transaction.createdoruser.status.updated. For a verification workflow, start withstatus.updatedanddata.updated. Multiple destinations let two systems receive the same decision at different URLs.Scaffold the Worker and store the secret as an environment secret.
npm create cloudflare@latest didit-webhook-handler cd didit-webhook-handler npx wrangler secret put DIDIT_WEBHOOK_SECRETWrangler prompts for the value. Paste the destination signing secret. It then lives in the Worker environment as
DIDIT_WEBHOOK_SECRETand never in the repository. During a rotation, bind the replaced secret separately asDIDIT_WEBHOOK_SECRET_PREVIOUS. The Worker verifies the current header with the first and the-Previousheader with the second. Delete the previous binding after the 24 hour window.Paste the Worker code into the scaffold entry file,
src/index.js. It uses Web Crypto, which the Workers runtime provides, and verifies the previous header with the previous secret instead of reusing the current secret.export default { async fetch(request, env) { if (request.method !== 'POST') { return new Response('Method Not Allowed', { status: 405 }); } if (!env.DIDIT_WEBHOOK_SECRET) { return new Response('Webhook secret not configured', { status: 500 }); } const timestamp = request.headers.get('X-Timestamp'); const signature = request.headers.get('X-Signature'); const previousSignature = request.headers.get('X-Signature-Previous'); if (!timestamp || !signature) { return new Response('Missing X-Timestamp or X-Signature', { status: 400 }); } const skew = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)); if (!Number.isFinite(skew) || skew > 300) { return new Response('Timestamp outside the 300 second window', { status: 403 }); } const rawBody = await request.text(); let verified = await verifySignature(env.DIDIT_WEBHOOK_SECRET, rawBody, signature); if (!verified && previousSignature && env.DIDIT_WEBHOOK_SECRET_PREVIOUS) { verified = await verifySignature(env.DIDIT_WEBHOOK_SECRET_PREVIOUS, rawBody, previousSignature); } if (!verified) { return new Response('Invalid signature', { status: 403 }); } let event; try { event = JSON.parse(rawBody); } catch (error) { return new Response('Error parsing JSON payload', { status: 400 }); } // Idempotency is your responsibility: deduplicate on event.event_id before changing state. // This sample only logs. console.log('didit webhook', event.event_id, event.webhook_type, event.status); return new Response('ok', { status: 200 }); }, }; // PSEUDOCODE: the shape of the check, not runnable verification code. Didit // documents HMAC-SHA256 over the signed bytes but not how the signature header // is encoded, so decodeSignatureHeader below has no implementation and this // sample cannot verify a real delivery yet. Deployment is blocked until Didit // confirms the header encoding. async function verifySignature(secret, body, headerValue) { if (!secret || !headerValue) return false; const signature = decodeSignatureHeader(headerValue); // encoding not documented if (!signature) return false; const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']); return crypto.subtle.verify('HMAC', key, signature, new TextEncoder().encode(body)); } // Not implemented on purpose. Decoding depends on the header encoding, which // Didit has not documented, so deployment is blocked until that is confirmed. function decodeSignatureHeader(headerValue) { throw new Error('Blocked: signature header encoding not documented'); }crypto.subtle.verifyis the runtime's constant-time comparison. You do not write your own byte loop, and you do not compare the previous header against the current secret. The signature check at the end of the file is pseudocode, not runnable code: the webhook reference does not state how the signature header is encoded, sodecodeSignatureHeaderhas no implementation and deployment is blocked until Didit confirms the encoding. Do not assume hex.Deploy and point the destination at the Worker.
npx wrangler deployWrangler prints the route, for example
https://didit-webhook-handler.your-subdomain.workers.dev. Paste it into the destination URL and save. Deliveries start on the next subscribed event.Send a test event from the console. The Try Webhook test sends
activity.created, which the reference documents as currently sent only by those tests. A 200 answer with the bodyok, plus one log line innpx wrangler tail, confirms the wiring.Run a sandbox session end to end. Sandbox events carry
environmentset tosandboxandsandbox_scenarionaming the armed scenario, or null when no scenario is armed and on live sessions. Nothing is charged in sandbox.Watch destination health with the list call, which returns 30 day delivery metrics for every destination.
curl -X GET 'https://verification.didit.me/v3/webhook/destinations/' \ -H 'x-api-key: $DIDIT_API_KEY'Read
health_status,failing_streak,deliveries_count,failed_deliveries_countanderror_rate_percentage. The single-destination call returns the signing secret and delivery summary.
Destination management calls
These are the documented webhook destination calls used in this guide. Create and rotate destinations in the Business Console. Read them through the Management API with the key in the x-api-key header.
| Call | Authentication | What it returns |
|---|---|---|
GET https://verification.didit.me/v3/webhook/destinations/ | x-api-key header | Every destination, its subscribed events, 30 day delivery metrics and health_status |
GET https://verification.didit.me/v3/webhook/destinations/{destination_uuid}/ | x-api-key header | One destination with its signing secret and delivery summary |
GET https://verification.didit.me/v3/organization/{organization_id}/application/{application_id}/webhook/destinations/{destination_uuid}/activity/ | x-api-key header, or a member Bearer token with read:webhooks | Failure alerts newest first, with occurred_at and failure_count, paginated with limit and offset |
Expected output
A valid event returns HTTP 200 with the body ok. npx wrangler tail shows one line per delivery with the event id, the webhook type and the status. Within a few deliveries the destination reports health_status of healthy and deliveries_count moving up.
A rejected request looks like one of these: 400 with Missing X-Timestamp or X-Signature when a proxy stripped the headers or you are testing by hand, 403 with Timestamp outside the 300 second window when the request is a copy dispatched more than 5 minutes ago, 403 with Invalid signature when the secret or the bytes are wrong. None of them change state. A 4xx answer to a real Didit delivery counts as a failed delivery attempt on our side, because a failed attempt is one your destination answered with HTTP 400 or above.
Inputs and outputs
| Name | Direction | What it is |
|---|---|---|
X-Timestamp | In | Unix epoch seconds when Didit dispatched the webhook |
X-Signature | In | HMAC-SHA256 over the exact raw bytes |
X-Signature-V2 | In | HMAC-SHA256 over the sorted, Unicode-preserved canonical JSON, the reference-recommended alternative for stacks that can rebuild it |
X-Signature-Simple | In | Deprecated envelope-only fallback over timestamp, session id, status and webhook type |
X-Signature-V2-Previous, X-Signature-Previous, X-Signature-Simple-Previous | In | The same signatures made with the replaced secret, sent for 24 hours after a rotation |
event_id | In | Idempotency key for the delivery |
webhook_type | In | The event family, for example status.updated |
status | In | Exact, case-sensitive session status string |
decision | In | Present only for Approved, Declined, In Review and Abandoned |
environment and sandbox_scenario | In | live or sandbox, and the armed scenario slug on sandbox sessions |
| 200 | Out | Accepted after signature, timestamp and JSON parse pass. The state update is your code's responsibility and should happen once per event_id. |
| 400, 403, 405 | Out | Rejected, no state change, recorded as a failed delivery attempt when the request came from Didit |
What the payload carries
The envelope includes event_id, session_id, status, webhook_type, created_at, timestamp, application_id, environment, sandbox_scenario, workflow_id, workflow_version, vendor_data and metadata. The decision object appears only for Approved, Declined, In Review and Abandoned, and it mirrors GET /v3/session/{session_id}/decision/. Per-feature results sit in plural arrays such as id_verifications[], liveness_checks[], face_matches[], aml_screenings[] and phone_verifications[], so one workflow can contain several instances of the same feature. KYB payloads add business_session_id and session_kind set to business, and the KYB equivalents are documented in the data models.

status.updated event, with per-feature results that also travel in the decision object.Status strings are exact and case sensitive. The ten values are Not Started, In Progress, Approved, Declined, In Review, Awaiting User, Resubmitted, Expired, Abandoned and Kyc Expired, the last one with a single capital K. Compare with strict equality and never lowercase them.

aml_screenings[] inside the same decision object the webhook carries.What x-webhook-key-phase means during a rotation
Didit does not send a header called x-webhook-key-phase. The key phase is visible from which headers arrive. In normal operation you get X-Signature and X-Signature-V2. For 24 hours after you rotate a destination signing secret in the Business Console, the same signatures also arrive in X-Signature-Previous, X-Signature-V2-Previous and X-Signature-Simple-Previous, made with the replaced secret. Bind the new secret as DIDIT_WEBHOOK_SECRET and the replaced one as DIDIT_WEBHOOK_SECRET_PREVIOUS. Verify the current header with the first and the -Previous header with the second, so verification keeps working while you deploy.
If you verify only with X-Signature-Simple, the reference says to re-fetch the decision from GET /v3/session/{session_id}/decision/ instead of trusting the payload. Outside a rotation window, return 4xx to anything that fails. A 4xx from a real Didit delivery counts as a failed attempt and pushes the destination toward degraded and then failing. A forged request that Didit never sent is not part of those metrics.
Failure cases and recovery
| Failure | What you see | Recovery |
|---|---|---|
| Body re-encoded before hashing | 403 Invalid signature on every real event, while the test event passes | Read the raw body first. Do not let a framework parse and re-serialize JSON before the HMAC |
| Wrong secret | 403 on every event | Use the secret of the destination in the same environment as the event. Sandbox and live secrets differ |
| Rotation without previous headers | 403 for a window after you change the secret | Bind the replaced secret as DIDIT_WEBHOOK_SECRET_PREVIOUS and verify X-Signature-Previous with it. Delete the binding after 24 hours |
| Node crypto import | Deploy or runtime error on createHmac | Use crypto.subtle, which the Workers runtime provides |
| Missing secret binding | 500 Webhook secret not configured | Run npx wrangler secret put DIDIT_WEBHOOK_SECRET for the environment you deployed |
| Stale copy | 403 Timestamp outside the 300 second window | Drop it. Older dispatches are not worth replaying by hand; read the decision endpoint instead |
| Double processing | Two state changes for one decision | Deduplicate on event_id in your storage. The sample only logs, so the deduplication is yours |
| Silent destination | No events at all | Check subscribed_events on the destination. There is no wildcard, so a missing family produces nothing |
| Endpoint down | health_status moves to degraded, then failing after 3 consecutive failed first attempts | Fix the route, then resend. A successful attempt, including a retry or resend, ends the streak |
Paid steps and review boundaries
- Sandbox is free on every plan and unlimited. Events there carry
environmentset tosandbox, and nothing is charged. - Live checks are billed per completed check from prepaid credit: full ID check $0.33, AML screening $0.20, KYB from $2.00 per company plus linked KYC and person AML per person.
- The delivery itself is not a published per-event line. The public price list prices checks, not webhook deliveries, so the webhook adds engineering work rather than a per-event fee. The Management API webhook endpoints are documented as pay-per-call.
- A
status.updatedcarrying In Review is a boundary, not an answer. A person decides in the Console, and that decision produces anotherstatus.updated. A reviewer, orPATCH /v3/session/{sessionId}/update-status/, can also move a session that already has a decision, so treat every event as the current state rather than the final one. - Investigator events separate machine from human:
investigator.decision.automatedis the Investigator deciding alone,investigator.decision.overriddenis a person taking another action. The event records which path was taken. workflow.compliance_changedarrives when the compliance status of a published workflow changes after a re-evaluation.- What Cloudflare charges you for the Worker sits outside Didit's price list.
Worked cost example
Take a month with 20,000 completed full ID checks and AML screening on 6,000 of those sessions. At list price: 20,000 x $0.33 = $6,600.00 for the ID checks, and 6,000 x $0.20 = $1,200.00 for AML. Total $7,800.00. Webhook delivery adds nothing to that total, because it is not a published per-event line.
On the Scale plan, which takes 10% off every Didit price, the same checks are 20,000 x $0.297 = $5,940.00 and 6,000 x $0.18 = $1,080.00, so $7,020.00. The plan is $299.00 a month with $350.00 of monthly credit, so the cash for that month is $299.00 + ($7,020.00 - $350.00) = $6,969.00. That is $831.00 less than the list total.

Sources
- Didit webhooks reference: signature headers, the 300 second window, event types and the envelope
- List webhook destinations API: health status, delivery metrics and
secret_last4 - Get webhook destination API: one destination with its signing secret and delivery summary
- Webhook destination failure activity API: failure alerts with timestamps and counts
- Didit data models: the decision arrays the webhook carries
- Verification statuses: the exact status strings and how a session moves
- API authentication: the
x-api-keyheader and key recovery - Didit API errors: status codes and which failures are safe to retry
- Pricing in the docs and didit.me/pricing: every price quoted here
- Integration prompt: the same recipe written for a coding agent
- Didit MCP server: reading the same data from an AI assistant
Next step: open business.didit.me, create a sandbox application, create a webhook destination and copy its signing secret. Didit sandbox testing runs there for free, and you can add credit only when you are ready to send live checks.
Try it
Try this in the sandbox
Run the check this guide describes, free.
The product this post is about, taken from its topic. Run it free in the sandbox.
Author
Alejandro Rosas
Co-founder and CTO

Questions
Frequently asked questions
How do I verify a Didit webhook signature on a Cloudflare Worker?
Read the raw body with request.text() before anything parses it, then recompute HMAC-SHA256 with the destination signing secret using crypto.subtle. Compare that value with X-Signature using crypto.subtle.verify, and during a rotation verify X-Signature-Previous with the replaced secret stored in its own binding. Reject the request when X-Timestamp is more than 300 seconds from now, and only then parse the JSON.
Should I verify X-Signature or X-Signature-V2?
The reference recommends X-Signature-V2 when your stack can rebuild the sorted, Unicode-preserved canonical JSON. This Worker sample verifies X-Signature over the exact bytes from request.text(), which is the one we can show end to end here, and it implements neither X-Signature-V2 nor the canonicalization that header needs. Use one path, not both, because the bytes hashed are different.
Why does my signature check fail when the secret is correct?
The usual cause is that something parsed and re-serialized the body before the HMAC, which changes the bytes. The second cause is a secret from the other environment, since sandbox and live destinations sign with different secrets. The third is a rotation window, when the current header uses the new secret and the event was signed with the old one, which arrives in the -Previous header and must be checked with the old secret.
Does Didit retry failed webhook deliveries?
Yes, deliveries are retried with bounds, and retries do not add to failing_streak. The exact retry schedule is not published in the webhook reference, so design your handler to be idempotent on event_id rather than to count attempts. A successful attempt, including a retry or a resend, ends the failure streak.
Does returning 403 to a forged request hurt destination health?
Only Didit delivery attempts affect destination health. A forged request that Didit never sent is not part of our metrics. A real delivery that your Worker rejects with a 4xx is a failed attempt, and three consecutive failed first attempts since the last success set health_status to failing.
What HTTP status should my Worker return to Didit?
Return a 2xx after the signature and timestamp checks pass and the body parses as JSON. The parse is local and cheap; the state write is what should happen once per event_id. A slow or failing answer counts against the destination, so keep the handler tight.
Which events should I subscribe to for a KYC workflow?
Start with status.updated and data.updated. Add entity families such as user.status.updated or business.status.updated only if you track entities, and add transaction.created for transaction monitoring. There is no wildcard, so an event family you do not list never arrives.
Are webhook status strings case sensitive?
Yes. Every status is an exact string, so In Review has a capital R and a space, and Kyc Expired uses a single capital K. Lowercasing or slugging the value before comparison is the most common reason a handler silently ignores a decision.
Does the decision object always arrive with an event?
No. decision is present only for Approved, Declined, In Review and Abandoned. Events for Not Started, In Progress, Awaiting User, Resubmitted, Expired and Kyc Expired carry the envelope without it, so a missing decision is not a broken payload.
Can I test Didit webhooks without paying?
Yes. Sandbox is free on every plan and nothing is charged there, and the Try Webhook test in the console sends an activity.created event to your destination. Sandbox sessions also let you arm a scenario, which arrives in sandbox_scenario on the event.
How do I find out that a destination is failing?
Call GET https://verification.didit.me/v3/webhook/destinations/ and read health_status, failing_streak, failed_deliveries_count and error_rate_percentage for the last 30 days. The destination activity endpoint lists recorded failure_alert entries with occurred_at and failure_count, paginated with limit and offset. Alert on failing, not on a single 4xx.
Compliance built in
Audited, certified and attested.
We hold the certifications and build each country's rules into your flows, so you can launch anywhere without worrying. Security and Compliance center
- Regulation encoded into your flows
Tell us what you do and where. Didit lists the rules that apply to you, with sources, and builds the checks each country needs into one workflow.
- Ready for AMLR
Every requirement of the new EU anti-money laundering rules, from checking customers to human review, is already covered by a Didit check.
- Tested in Spain's Treasury sandbox
Spain's Treasury published its supervised sandbox report on Didit's NFC plus active liveness onboarding; SEPBLAC took part and valued the added measures positively.
- Audited, not self-declared
iBeta Level 1 and Level 2. Liveness tested under ISO/IEC 30107-3.
Your obligations · 3 regions
SOC 2 Type 2
ISO 27001
iBeta Level 1 and Level 2
EU regulator attestation
FSM youth protection
GDPR
EBA remote onboarding
MiCA compatible
FIDO Alliance member
- AMLREU AML Regulation ready
Integration · Didit MCP
Run Didit from your own AI agent
Connect Didit to Claude, Cursor, VS Code or ChatGPT and just ask in plain words. Your agent can do anything you can do in the console, with the same permissions you have.
- Build workflowsDescribe the checks you need. The agent creates and publishes the flow.
- Run investigationsAsk why a session was declined, review cases, search people and companies.
- Change rulesCreate payment rules, test them on past data and switch them on.
- Pull reportsAsk for numbers, exports or the audit log.
Didit Academy


