Skip to main content

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.

Securing Webhooks with Cloudflare Workers: A Didit Guide

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.

Didit webhooks on Cloudflare Workers at a glance
ItemWhat to use
EndpointA POST route on your Worker, for example https://didit-webhook-handler.your-subdomain.workers.dev
Headers to verifyX-Timestamp plus X-Signature in this sample. X-Signature-V2 is the reference-recommended alternative when your stack can rebuild the canonical JSON.
Freshness window300 seconds between now and X-Timestamp
AlgorithmHMAC-SHA256 with the destination signing secret
RotationFor 24 hours after a secret rotation, the current headers use the new secret and the -Previous headers use the replaced secret. Bind them separately.
EventsExact names in subscribed_events, with no wildcard
Reply2xx 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 eventsFull 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

  1. 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 call GET /v3/webhook/destinations/{destination_uuid}/. A destination also gives you the rotation window described below, which the legacy webhook_url never receives.

  2. Subscribe to the events you need. subscribed_events takes exact names such as status.updated, data.updated, transaction.created or user.status.updated. For a verification workflow, start with status.updated and data.updated. Multiple destinations let two systems receive the same decision at different URLs.

  3. 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_SECRET

    Wrangler prompts for the value. Paste the destination signing secret. It then lives in the Worker environment as DIDIT_WEBHOOK_SECRET and never in the repository. During a rotation, bind the replaced secret separately as DIDIT_WEBHOOK_SECRET_PREVIOUS. The Worker verifies the current header with the first and the -Previous header with the second. Delete the previous binding after the 24 hour window.

  4. 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.verify is 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, so decodeSignatureHeader has no implementation and deployment is blocked until Didit confirms the encoding. Do not assume hex.

  5. Deploy and point the destination at the Worker.

    npx wrangler deploy

    Wrangler 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.

  6. 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 body ok, plus one log line in npx wrangler tail, confirms the wiring.

  7. Run a sandbox session end to end. Sandbox events carry environment set to sandbox and sandbox_scenario naming the armed scenario, or null when no scenario is armed and on live sessions. Nothing is charged in sandbox.

  8. 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_count and error_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.

Webhook destination calls and authentication
CallAuthenticationWhat it returns
GET https://verification.didit.me/v3/webhook/destinations/x-api-key headerEvery destination, its subscribed events, 30 day delivery metrics and health_status
GET https://verification.didit.me/v3/webhook/destinations/{destination_uuid}/x-api-key headerOne 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:webhooksFailure 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

What your Worker receives and what it returns
NameDirectionWhat it is
X-TimestampInUnix epoch seconds when Didit dispatched the webhook
X-SignatureInHMAC-SHA256 over the exact raw bytes
X-Signature-V2InHMAC-SHA256 over the sorted, Unicode-preserved canonical JSON, the reference-recommended alternative for stacks that can rebuild it
X-Signature-SimpleInDeprecated envelope-only fallback over timestamp, session id, status and webhook type
X-Signature-V2-Previous, X-Signature-Previous, X-Signature-Simple-PreviousInThe same signatures made with the replaced secret, sent for 24 hours after a rotation
event_idInIdempotency key for the delivery
webhook_typeInThe event family, for example status.updated
statusInExact, case-sensitive session status string
decisionInPresent only for Approved, Declined, In Review and Abandoned
environment and sandbox_scenarioInlive or sandbox, and the armed scenario slug on sandbox sessions
200OutAccepted after signature, timestamp and JSON parse pass. The state update is your code's responsibility and should happen once per event_id.
400, 403, 405OutRejected, 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.

A session detail in the Didit Business Console showing AML screening results
The session behind a 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 screening results for a session in the Didit Business Console
AML results arrive in 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

Common failures on a Worker webhook endpoint
FailureWhat you seeRecovery
Body re-encoded before hashing403 Invalid signature on every real event, while the test event passesRead the raw body first. Do not let a framework parse and re-serialize JSON before the HMAC
Wrong secret403 on every eventUse the secret of the destination in the same environment as the event. Sandbox and live secrets differ
Rotation without previous headers403 for a window after you change the secretBind the replaced secret as DIDIT_WEBHOOK_SECRET_PREVIOUS and verify X-Signature-Previous with it. Delete the binding after 24 hours
Node crypto importDeploy or runtime error on createHmacUse crypto.subtle, which the Workers runtime provides
Missing secret binding500 Webhook secret not configuredRun npx wrangler secret put DIDIT_WEBHOOK_SECRET for the environment you deployed
Stale copy403 Timestamp outside the 300 second windowDrop it. Older dispatches are not worth replaying by hand; read the decision endpoint instead
Double processingTwo state changes for one decisionDeduplicate on event_id in your storage. The sample only logs, so the deduplication is yours
Silent destinationNo events at allCheck subscribed_events on the destination. There is no wildcard, so a missing family produces nothing
Endpoint downhealth_status moves to degraded, then failing after 3 consecutive failed first attemptsFix the route, then resend. A successful attempt, including a retry or resend, ends the streak
  • Sandbox is free on every plan and unlimited. Events there carry environment set to sandbox, 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.updated carrying In Review is a boundary, not an answer. A person decides in the Console, and that decision produces another status.updated. A reviewer, or PATCH /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.automated is the Investigator deciding alone, investigator.decision.overridden is a person taking another action. The event records which path was taken.
  • workflow.compliance_changed arrives 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.

How Didit billing works with credits, auto-recharge and volume discounts
Credits, auto-recharge and plan discounts, which is where the $831.00 difference comes from.

Sources

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.

ID Verification

The product this post is about, taken from its topic. Run it free in the sandbox.

$0.15 per checkStart free

Author

Alejandro Rosas

Co-founder and CTO

Alejandro Rosas

Alejandro Rosas

Co-founder and CTO

About Didit

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.

Compliance assistant

Your obligations · 3 regions

EU · AMLRCustomer due diligence, human reviewCovered
Illinois, Texas, ColoradoExplicit biometric consentCovered
Germany · Youth protectionVerified adults only (JMStV)Covered
Workflow checked. Every obligation is met
  • 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.

Add to ClaudeChatGPT
Didit Academy · Lesson 04 · Use Didit with MCP
  • 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.

Verify your first user today.

Start free

Free sandbox. Credit applies to work-email sign-ups.