Secure Your Node.js Backend: HMAC Validation for Didit Webhooks
Read the raw body, verify the signature with the official Node SDK verifier before any parsing, accept X-Signature-V2-Previous during a secret rotation, then parse, deduplicate on event_id and reject timestamps older than 300.

Contents
In this guide
Jump to the part you need.
This guide is for engineers running a Node.js service that receives Didit webhooks. You finish with an endpoint that verifies the HMAC-SHA256 signature, limits payload age, and deduplicates on event_id before any change is applied. Webhook delivery is not a billed line in our price book; the checks that trigger it are, and a full KYC check is $0.33. The caveat that breaks most first attempts: read the raw request body before any JSON middleware does.
Last updated: November 26, 2026. Prices checked against the live Didit price feed on November 26, 2026.
| Control | What Didit sends | What your code does |
|---|---|---|
| Signature, recommended | X-Signature-V2: HMAC-SHA256 over the sorted, Unicode-preserved canonical JSON | Recompute with the destination signing secret and compare in constant time |
| Signature, raw bytes | X-Signature: HMAC-SHA256 over the exact raw request bytes | Use only when your stack does not re-encode the body |
| Deprecated signature | X-Signature-Simple: covers timestamp, session id, status and webhook type only | Authenticates the envelope, not the decision. Re-fetch the decision from GET /v3/session/{session_id}/decision/ |
| Freshness | X-Timestamp: Unix epoch seconds | Reject when the absolute difference from now is greater than 300 seconds |
| Secret rotation | X-Signature-V2-Previous, sent for 24 hours after a rotation, made with the replaced secret | Hold the replaced secret separately, sign the same canonical string with it, and accept a match on either header while you deploy |
| Replay inside the window | The same event_id on a retry or a resent payload | Record event_id before applying the change and skip one you have already applied |
| Response | Bounded retries on failed deliveries | Return 2xx quickly and update state idempotently |
Start free in the sandbox at business.didit.me, no sales call, and sandbox testing is free and unlimited. Developers who want an assistant to read sessions and destinations can connect Didit through the MCP server. Unit prices for every module are on the pricing page.
What the finished endpoint does
You end up with one POST route, /api/webhooks/didit, that runs these checks in order: read the raw bytes of the request, confirm the timestamp is fresh, verify the signature over those bytes before any JSON parsing, accept a match on X-Signature-V2-Previous while a rotated secret is being deployed, parse the body only after it verifies, and record event_id before applying anything. Anything that fails a check gets a 4xx and no state change.
The recommended method is X-Signature-V2 over canonical JSON, because it survives a proxy or framework that reorders or re-encodes JSON keys. The docs describe three primary signature headers, plus the rotation-specific previous-signature headers, and name V2 as the one to use. Our webhook guide is at docs.didit.me/integration/webhooks.
X-Signature-V2signs the sorted, Unicode-preserved canonical JSON of the payload.X-Signaturesigns the exact raw request bytes. They are different byte strings over the same event, so choose one and implement that one: V2 needs a deterministic re-serialization, raw bytes need the Buffer untouched.
Prerequisites
- Node.js 18 or later. The official
@didit-protocol/sdk-nodepackage supports Node.js 18, Bun, Deno and edge runtimes withfetch. - The
expressandcryptomodules.cryptoships with Node.js; install Express with npm. - A Didit application with at least one webhook destination and its signing secret. The Business Console creates destinations, and
GET /v3/webhook/destinations/{destination_uuid}/returns the full secret. The list endpoint returns onlysecret_last4. - The secret stored in an environment variable, not in the repository, and the replaced secret in its own variable while you rotate.
- A host clock kept in sync over NTP, because the freshness window is 300 seconds.
- A sandbox application to test with. Nothing is charged in sandbox.
Steps to validate a Didit webhook in Node.js
- Create the destination and copy the signing secret. Choose the exact event names you want, because there is no wildcard. Include every family you need, for example
status.updated,data.updated,transaction.createdandinvestigator.report.ready. Store the secret asDIDIT_WEBHOOK_SECRET. - Install Express in an empty folder. Two commands are enough.
- Read the raw body. Use
express.raw({ type: '*/*' })on the webhook route soreq.bodyis a Buffer. Do not putexpress.json()in front of this route. - Verify the signature before parsing. Use the official Node SDK verifier for
X-Signature-V2, or verifyX-Signatureover the untouched raw bytes, and only then parse the body. Compare each header against an HMAC generated with its corresponding secret:X-Signature-V2with the current secret andX-Signature-V2-Previouswith the replaced secret, usingcrypto.timingSafeEqualand never===. - Enforce the freshness window. Reject when the absolute difference between now and
X-Timestampis greater than 300 seconds. This caps how long a captured payload stays usable. A replay that lands inside the window is caught by theevent_idrecord in step 7. - Branch on the event. Read
webhook_type, thenstatusif the type isstatus.updated. Status strings are exact and case sensitive:Approved,Declined,In Review,In Progress,Not Started,Awaiting User,Resubmitted,Expired,Abandoned,Kyc Expired. Note the single capital K inKyc Expired. - Record the event id, then answer 2xx. Write
event_idto your own store before you apply the change, return200, and skip anyevent_idyou have already recorded so a retry does not apply the same change twice. - Test in sandbox, then watch destination health. Fire a test delivery from the Console, confirm a 200 in your logs, then read
health_status,failing_streakanderror_rate_percentagefromGET https://verification.didit.me/v3/webhook/destinations/with yourx-api-keyheader. For the failure alerts of one destination, callGET https://verification.didit.me/v3/organization/{organization_id}/application/{application_id}/webhook/destinations/{destination_uuid}/activity/with all three path values: your organization id, your application id and the destination uuid. It returnsid,type,occurred_atandfailure_count, newest first, paginated withlimitandoffset.
mkdir didit-webhook && cd didit-webhook
npm init -y
npm install express
Here is the complete file. It follows the documented sequence: raw body first, signature verified before any parsing, then the event. Two pieces are yours to supply: the call into the official Node SDK verifier, and the event-id record, which uses an in-memory Set here so the control flow is visible and should be replaced with a store that enforces uniqueness.
const express = require('express');
const app = express();
const TOLERANCE_SECONDS = 300;
// Application-specific: replace this in-memory Set with your own store,
// for example a table with a unique constraint on event_id.
const seenEvents = new Set();
app.post('/api/webhooks/didit', express.raw({ type: '*/*', limit: '2mb' }), async function (req, res) {
const rawBody = req.body;
const timestamp = req.headers['x-timestamp'];
const signature = req.headers['x-signature-v2'];
// 1. Envelope check.
if (!Buffer.isBuffer(rawBody) || !timestamp || !signature) {
return res.status(400).json({ error: 'missing_signature_headers' });
}
// 2. Freshness: abs(now - X-Timestamp) must be 300 seconds or less.
const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
if (!Number.isFinite(age) || age > TOLERANCE_SECONDS) {
return res.status(401).json({ error: 'stale_timestamp' });
}
// 3. Verify the untouched raw bytes before parsing. verifyWithDiditSdk is your
// call into the official Node SDK verifier: it checks X-Signature-V2 and,
// when present, X-Signature-V2-Previous, and handles the header encoding.
// If you verify by hand, use X-Signature over these same raw bytes.
let verified;
try {
verified = await verifyWithDiditSdk(rawBody, req.headers);
} catch (err) {
verified = false;
}
if (!verified) {
return res.status(401).json({ error: 'invalid_signature' });
}
// 4. Verified. Only now parse the JSON body.
let event;
try {
event = JSON.parse(rawBody.toString('utf8'));
} catch (err) {
return res.status(400).json({ error: 'invalid_json' });
}
// 5. Verified. Record the event id before applying the change.
if (seenEvents.has(event.event_id)) {
return res.status(200).json({ received: true, duplicate: true });
}
seenEvents.add(event.event_id);
console.log('verified', event.webhook_type, event.event_id, event.session_id, event.status);
res.status(200).json({ received: true });
});
app.listen(3000, function () {
console.log('listening on 3000');
});
Two notes on that file. The signature encoding and the rotation comparison stay inside the official Node SDK verifier: it verifies X-Signature-V2 using Didit's documented canonical JSON serialization and, when present, accepts a match on X-Signature-V2-Previous so verification keeps working while a rotated secret is deployed. If you verify by hand, use X-Signature over the untouched raw bytes before parsing, because that is the only header computed over the exact raw bytes. The seenEvents Set is illustrative, not restart-safe: duplicate handling is your implementation concern, guided by Didit's idempotency requirement, and a real deployment needs the event_id write to succeed before the change is applied so a crash between the two cannot replay the event.
Expected output
A delivery that passes every check answers with a 200 and one log line. The identifiers below are shortened for readability.
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{"received":true}
server log:
verified status.updated 0b0f8f2e-... 8a1c4b7d-... Approved
A second delivery of the same event is acknowledged and not applied again.
HTTP/1.1 200 OK
{"received":true,"duplicate":true}
A payload with a wrong signature, or one older than five minutes, never reaches your business logic.
HTTP/1.1 401 Unauthorized
{"error":"invalid_signature"}
HTTP/1.1 401 Unauthorized
{"error":"stale_timestamp"}
HTTP/1.1 400 Bad Request
{"error":"missing_signature_headers"}

status.updated payload.Inputs and outputs
| Name | Direction | Type | What it carries |
|---|---|---|---|
X-Signature-V2 | in | header | HMAC-SHA256 over the sorted, Unicode-preserved canonical JSON. Recommended. |
X-Signature-V2-Previous | in | header | The same signature made with the replaced secret, sent only for 24 hours after a rotation. |
X-Signature | in | header | HMAC-SHA256 over the exact raw request bytes. |
X-Signature-Simple | in | header | Deprecated. Covers timestamp, session id, status and webhook type only. |
X-Timestamp | in | header | Unix epoch seconds when Didit dispatched the webhook. |
| Envelope | in | JSON body | event_id, session_id, status, webhook_type, created_at, application_id, environment, workflow_id, vendor_data, metadata, and decision when there is one. |
| 2xx | out | response | Accepted. Keep the body small. |
| 400 | out | response | Missing headers, or a body that is not JSON. |
| 401 | out | response | Stale timestamp or signature mismatch. |
Failure cases and recovery
| Symptom | Likely cause | Recovery |
|---|---|---|
| Every delivery returns 400 for missing headers | A proxy strips custom headers, or a JSON parser ran first and emptied the raw body | Allow X-Signature-V2 and X-Timestamp through, and mount the raw parser on the webhook route only |
| Signature mismatch with the correct secret | JSON middleware re-serialized the body, or the signature was checked after parsing | Verify X-Signature over the exact raw bytes before parsing, or use the official Node SDK verifier for X-Signature-V2 |
| Signature is valid but the timestamp is rejected | Host clock drift | Sync the host over NTP. The window is 300 seconds |
| Mismatch right after a secret rotation | The replaced secret is not loaded, or the new one is deployed on one side only | Hold the replaced secret in its own variable, sign with it to check X-Signature-V2-Previous, and finish the rollout inside 24 hours |
| Signature passes but the decision is missing | The status is not a decision status, or the destination only subscribes to data.updated | decision arrives only on Approved, Declined, In Review and Abandoned. Otherwise call GET /v3/session/{session_id}/decision/ |
| The same event arrives several times | Your endpoint answered slowly or with a 5xx, or a replay landed inside the 300-second window | Answer 2xx after the event_id is recorded. Duplicate handling is your implementation concern: keep the event_id record unique and durable so a repeat cannot be applied twice. The in-memory Set in the sample is illustrative and not restart-safe. |
| Destination health shows failing | Three or more consecutive events failed their first delivery attempt since the destination last answered successfully | Read health_status and failing_streak from GET https://verification.didit.me/v3/webhook/destinations/, then list the failure alerts with GET https://verification.didit.me/v3/organization/{organization_id}/application/{application_id}/webhook/destinations/{destination_uuid}/activity/ |

aml_screenings[].Event types you will subscribe to
Event names are exact strings and there is no wildcard, so include every family you want to receive. The session and entity families are status.updated, data.updated, user.status.updated, user.data.updated, business.status.updated and business.data.updated. Transaction and workflow families include transaction.created, transaction.status.updated, travel_rule.status.updated, workflow.compliance_changed and transaction_rule_suggestions.created. The Investigator writes a group of its own events, such as investigator.report.ready, investigator.decision.automated and investigator.rfi.overdue. activity.created is reserved for the activity timeline and is currently only sent by Try Webhook tests. You can create several destinations to fan out to different URLs.
KYB payloads add business_session_id and session_kind set to business. Read the full status lifecycle at verification statuses and the decision shape at data models.
Rotating the signing secret without dropping events
When you rotate a destination secret in the Business Console, Didit keeps signing with the replaced secret for 24 hours alongside the new one and sends those values in X-Signature-V2-Previous, X-Signature-Previous and X-Signature-Simple-Previous. Keep both secrets in separate variables for the length of the rotation window:
# during the 24-hour rotation window only
DIDIT_WEBHOOK_SECRET=the-new-secret-from-the-console
DIDIT_WEBHOOK_SECRET_PREVIOUS=the-secret-being-replaced
Sign the canonical payload twice, once per variable, and accept a match on either header. Then remove the previous variable once the header stops arriving. Never sign with both secrets in one HMAC call or compare the current signature against the previous header: a value made with the replaced secret will not match a value made with the new one. The legacy application webhook_url never receives the previous headers, which is one more reason to use destinations.
Paid steps, free steps and where a human decides
Creating destinations, signing, retries and HMAC verification have no separate line in the price book. The paid part is the check that produced the event: a full KYC check at $0.33, AML screening at $0.20, a KYB registry retrieval from $2.00, wallet screening at $0.15, transaction monitoring at $0.001 per transaction. Sandbox deliveries cost nothing, which is why you build the endpoint in sandbox first.
The review boundary sits at the In Review status. Automated checks flagged something, and a compliance reviewer approves, declines or requests a resubmission in the Console or through the API. Your handler should record that state and notify the right person. It should not auto-approve a session that a reviewer has not seen. An approved session can also move to Kyc Expired later, when the verified document passes its expiry date, so handle that event too.
What this costs at volume
Take a program that completes 10,000 full KYC checks and 2,500 AML screenings in a month. At list price:
- Full KYC: 10,000 x $0.33 = $3,300.00
- AML screening: 2,500 x $0.20 = $500.00
- Total for the month: $3,300.00 + $500.00 = $3,800.00
On the Scale plan, which takes 10% off every Didit price, the same month works out as 10,000 x $0.297 = $2,970.00 for KYC and 2,500 x $0.18 = $450.00 for AML, so $3,420.00 in checks plus the $299.00 monthly fee, $3,719.00 in total. At that volume the discount is larger than the fee. The Free plan starts with $10.00 of credit each month, and the sandbox is free on every plan. Plan terms and the estimator are on didit.me/pricing.

If you are moving an existing identity stack over, didit.me/switch covers the migration path. For transaction events, see transaction monitoring, and for screening results inside a session, see AML screening.

Sources
- Didit webhooks guide: signatures, headers, retries, payloads
- Didit verification statuses
- Didit data models
- Didit server SDKs overview and Node.js SDK
- List webhook destinations API
- Webhook destination failure activity API
- Didit API errors
- Didit pricing and pricing in the docs
Next step: create a sandbox application at business.didit.me, add a webhook destination, point it at the route above and fire a test delivery. There is no sales call, and sandbox testing is free and unlimited.
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
Which signature header should I verify for Didit webhooks?
Verify X-Signature-V2. It is HMAC-SHA256 over the sorted, Unicode-preserved canonical JSON of the payload and is the header Didit recommends. X-Signature signs the exact raw request bytes and only works when your stack does not re-encode the body. X-Signature-Simple is deprecated and covers the envelope only.
How much clock skew does Didit allow on a webhook?
300 seconds. The documented check is that the absolute difference between now and X-Timestamp, in Unix epoch seconds, is 300 or less. Anything older is treated as a possible replay and should be rejected with a 401.
Why does my HMAC signature fail even with the right secret?
Almost always because the bytes changed. A JSON body parser such as express.json() re-serializes the payload, so the string you hash is not the bytes Didit signed. Mount express.raw({ type: '*/*' }) on the webhook route only, then verify with the official Node SDK verifier for X-Signature-V2, or verify X-Signature over the untouched raw bytes. Parse the JSON only after the signature verifies.
Does Didit retry a webhook if my endpoint returns an error?
Yes. Didit retries failed deliveries and publishes the retry policy in the webhooks guide, with delivery metrics per destination. Answer with a 2xx as soon as the payload is verified and the event_id is recorded, and treat repeat deliveries as normal rather than exceptional.
Do I have to parse the JSON before verifying the signature?
No. The documented sequence is to read the raw body first and verify before parsing. The official Node SDK verifier follows that sequence. If you implement it yourself, verify X-Signature over the exact raw bytes. The V2 header covers canonical JSON, so use the SDK verifier for V2 rather than parsing the body yourself.
Does the 300-second timestamp window stop replayed webhooks?
It caps how old a captured payload can be, so a replay stops working after five minutes. A replay that lands inside those five minutes still passes the timestamp check, which is why you record event_id before applying the change and skip an id you have already stored.
How do I rotate the Didit webhook secret without dropping events?
Rotate in the Business Console, keep the replaced secret in its own environment variable, then accept a match on either X-Signature-V2 or X-Signature-V2-Previous, signing the payload once with each secret. Didit keeps sending the signatures made with the replaced secret for 24 hours, which is enough time to deploy the new value everywhere.
What event types can I subscribe to?
Exact names such as status.updated, data.updated, user.status.updated, business.data.updated, transaction.created, travel_rule.status.updated and the Investigator family. There is no wildcard, so a destination only receives the events listed in its subscribed_events.
What HTTP status should my webhook endpoint return?
Return 200 when the payload is verified and the event_id is recorded. Return 400 for missing headers or a body that is not JSON, and 401 for a stale timestamp or a signature mismatch. Keep the response fast and small, and let the state update happen against your own event_id record.
Is webhook delivery billed separately by Didit?
No. The price book has no line for webhooks or signature verification. You pay per completed check: $0.33 for a full KYC check, $0.20 for AML screening, from $2.00 for a KYB registry retrieval. Sandbox testing is free and unlimited.
What are the exact session status strings in a Didit webhook?
Not Started, In Progress, Approved, Declined, In Review, Awaiting User, Resubmitted, Expired, Abandoned and Kyc Expired. They are case sensitive, include the space, and Kyc Expired uses a single capital K. Match them with strict string equality.
Can I use the Didit Node SDK instead of writing the HMAC check myself?
Yes. The official @didit-protocol/sdk-node package calls the server APIs with typed requests and verifies the webhooks Didit sends you. Install it with npm install @didit-protocol/sdk-node and read the Node page at docs.didit.me/integration/server-sdks/node. The sample above uses that verifier for the signature check and keeps the rest of the handler visible.
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


