Express.js Middleware for Dynamic Identity Verification (2026)
Build an Express middleware that chooses a Didit workflow per request, creates a session, then gates the protected route on the signed webhook decision. Full ID check costs $0.33.

Contents
In this guide
Jump to the part you need.
This page shows how to build an Express.js middleware that picks a Didit workflow per request, so a small top-up and a large withdrawal do not get the same checks. It fits Node teams that already have auth and want risk-based verification behind their own routes. You pay per completed check, from $0.33 per full ID check. The caveat: the middleware cannot approve anyone inside the same request. A signed webhook delivers the decision later.
Last updated: November 26, 2026. Prices checked against the live Didit price feed on November 26, 2026.
The middleware at a glance
| Piece | What it does | Price |
|---|---|---|
POST /v3/session/ | Creates a session for the workflow your rule picked, returns a hosted URL | Billed per completed check, not per API call |
| Hosted flow, JS SDK or iframe | Where the user does the steps: email code, phone code, ID document, liveness, AML | Full ID check $0.33, email verification $0.02, US SMS code $0.0473, AML screening $0.20 |
GET /v3/session/{session_id}/decision/ | Reads the full decision record after the fact | Included |
Webhook status.updated | Signed server-to-server event when the status changes | Included |
| Workflow Orchestrator | Holds the step order and conditional logic outside your code | Free |
Start free in the sandbox at https://business.didit.me/, no sales call, and every sandbox check is mocked so tests cost nothing. If you would rather have an AI assistant write the integration, connect Didit to one through the MCP server. Unit prices for every module sit on the Didit pricing page and in the pricing docs.
Outcome and the method we recommend
The outcome is three things working together. A route that returns a verification URL for the workflow the request deserves. A server endpoint that receives the signed decision and records it. A guard that only lets an approved user reach the protected handler. Everything else, meaning which steps run and in what order, stays in the Didit workflow so you can change it without a deploy.
We recommend the hosted flow for the user experience and the Session API plus webhooks for the logic. The web page stays simple: your middleware returns a URL, the client sends the browser there, and the user sees the Didit flow with your branding. The decision arrives on your server, signed. Do not try to run checks inside the request, and do not treat the browser redirect as proof, because the user controls the browser. The redirect is a return path, not evidence. A hit on the callback URL must never change approval state in your database. Use the signed webhook, or reconcile with the decision endpoint.
Two different callbacks exist and teams mix them up. The callback field on session creation is where the browser lands at the end, with ?verificationSessionId={session_id}&status={status} appended. The webhook is the server-to-server, HMAC-signed event that your middleware should trust. Build the guard on the webhook. More than 4,000 companies run identity and fraud checks through Didit today, and the same session plus webhook pattern covers all of them.
Prerequisites
- Node.js 18 or newer, so the global
fetchexists, plusexpress. - A Didit organization and an application. Create one at business.didit.me and take the key from Developers, then API keys. New sandbox keys start with
sk_test_and new live keys withsk_live_. Keys created before this format have no prefix and keep working. Keep the key server side only. Details are in API authentication. - Two published workflows in the Business Console: one light (email plus phone, for example) and one heavy (ID document, liveness, face match, AML screening). Each has a stable
workflow_idUUID. See Create Session. - Your own auth layer, so you know the user id before you decide anything. The middleware assumes
req.user.id. - A publicly reachable HTTPS endpoint for webhooks, or a tunnel while you test.
Build it, step by step
- Create the sandbox application and copy the key. In the Business Console open Developers, then API keys, and copy the primary key of the sandbox application. Put it in
DIDIT_API_KEY. Never ship it to a browser bundle. - Publish two workflows and note their ids. Build the light workflow and the heavy workflow in the console, then store the two UUIDs as
DIDIT_WORKFLOW_LOWandDIDIT_WORKFLOW_HIGH. You can add or remove steps later in the console, and your code keeps calling the sameworkflow_id. - Install and configure. Run
npm install express, then setDIDIT_API_KEY,DIDIT_WORKFLOW_LOW,DIDIT_WORKFLOW_HIGH,DIDIT_WEBHOOK_SECRETand, only during a secret rotation,DIDIT_WEBHOOK_SECRET_PREVIOUSin the environment. - Write the session middleware. One function, one decision, one API call. The rule that picks the workflow is yours. This is the runnable example.
// verification.js const DIDIT_BASE = 'https://verification.didit.me'; // Replace this with your own risk rule or policy lookup. function pickWorkflow(req) { const amount = Number(req.body.amount || 0); return amount >= 1000 ? process.env.DIDIT_WORKFLOW_HIGH // ID document + liveness + AML : process.env.DIDIT_WORKFLOW_LOW; // email + phone } async function startVerification(req, res) { const response = await fetch(DIDIT_BASE + '/v3/session/', { method: 'POST', headers: { 'x-api-key': process.env.DIDIT_API_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ workflow_id: pickWorkflow(req), vendor_data: req.user.id, callback: 'https://your-app.com/return', metadata: { route: req.path, amount: req.body.amount } }) }); if (response.status === 429) { // The rate-limit response carries a wait field in seconds. const detail = await response.json().catch(() => ({})); return res.status(503).json({ error: 'verification_unavailable', retry_after: detail.wait ?? null }); } if (response.status === 401 || response.status === 403) { return res.status(503).json({ error: 'verification_unavailable' }); } if (!response.ok) { return res.status(502).json({ error: 'session_not_created' }); } const session = await response.json(); // Send the URL to your client, or use res.redirect(session.url) return res.status(202).json({ status: 'verification_required', url: session.url }); } module.exports = { startVerification }; - Write the status store. This is your own persistence, not a Didit one. It has to survive a restart and it has to be atomic, so keep the status and the applied
event_idvalues in your database. A process-local Map and Set are lost when the process restarts, and two concurrent deliveries can both pass the check and apply the same event twice. Insert theevent_idwith an insert-or-ignore, and update the status only when that insert actually created a row. Both statements go in one transaction.// store.js // Application-owned persistence. Keep this in your database, not in process memory. // didit_events(event_id uuid PRIMARY KEY, user_id text, status text) // didit_status(user_id text PRIMARY KEY, status text) const db = require('./db'); // your database pool async function saveStatus(eventId, userId, status) { const client = await db.connect(); try { await client.query('BEGIN'); // Atomic insert-or-ignore on event_id. rowCount is 0 when the event already existed. const inserted = await client.query( 'INSERT INTO didit_events (event_id, user_id, status) VALUES ($1, $2, $3) ON CONFLICT (event_id) DO NOTHING', [eventId, userId, status] ); // Move the status only when this delivery is the one that inserted the event. if (inserted.rowCount === 1) { await client.query( 'INSERT INTO didit_status (user_id, status) VALUES ($1, $2) ON CONFLICT (user_id) DO UPDATE SET status = EXCLUDED.status', [userId, status] ); } await client.query('COMMIT'); } catch (err) { await client.query('ROLLBACK'); throw err; } finally { client.release(); } } async function getStatus(userId) { const result = await db.query('SELECT status FROM didit_status WHERE user_id = $1', [userId]); return result.rows[0] ? result.rows[0].status : null; } module.exports = { saveStatus, getStatus }; - Mount the routes in the right order. The webhook handler needs the raw request bytes, so it must be mounted before
express.json(). A global JSON parser consumes the stream first and the signature check then fails.// server.js const express = require('express'); const { startVerification } = require('./verification'); const { requireApprovedUser } = require('./guard'); const { diditWebhook } = require('./webhook'); const app = express(); // Webhook first: raw bytes, before any JSON parser runs. app.post('/webhooks/didit', express.raw({ type: 'application/json' }), diditWebhook); app.use(express.json()); app.post('/api/withdraw', requireAuth, startVerification); app.post('/api/withdraw/confirm', requireAuth, requireApprovedUser, (req, res) => { res.json({ ok: true }); }); - Add the webhook endpoint and verify the signature. Check the timestamp window, then accept the event only when a supported signature matches:
X-SignatureorX-Signature-Previousover the raw request bytes, orX-Signature-V2orX-Signature-V2-Previousover the sorted canonical JSON of the parsed event.X-Signature-V2is the recommended one and survives a stack that re-encodes JSON. Accept the previous-signature headers for 24 hours after a secret rotation, return 2xx immediately, then write state idempotently. The headers are documented in Webhooks.// webhook.js const crypto = require('crypto'); const { saveStatus } = require('./store'); // Sorted, Unicode-preserving canonical JSON, as the docs describe for X-Signature-V2. function canonicalJson(value) { if (value === null || typeof value !== 'object') return JSON.stringify(value); if (Array.isArray(value)) return '[' + value.map(canonicalJson).join(',') + ']'; const keys = Object.keys(value).sort(); return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonicalJson(value[k])).join(',') + '}'; } function sign(payload, secret) { return crypto.createHmac('sha256', secret).update(payload).digest('hex'); } function sameSignature(received, expected) { const a = Buffer.from(expected); const b = Buffer.from(received || ''); return a.length === b.length && crypto.timingSafeEqual(a, b); } function diditWebhook(req, res) { const timestamp = Number(req.header('X-Timestamp')); if (!timestamp || Math.abs(Date.now() / 1000 - timestamp) > 300) { return res.sendStatus(401); } // Accept the current secret and, for 24 hours after a rotation, the previous one. const secrets = [process.env.DIDIT_WEBHOOK_SECRET]; if (process.env.DIDIT_WEBHOOK_SECRET_PREVIOUS) { secrets.push(process.env.DIDIT_WEBHOOK_SECRET_PREVIOUS); } const matchesAny = (header, payload) => Boolean(header) && secrets.some((secret) => sameSignature(header, sign(payload, secret))); // Step 1: check the raw-byte signature when the sender sent one. const raw = req.body.toString(); const rawOk = matchesAny(req.header('X-Signature'), raw) || matchesAny(req.header('X-Signature-Previous'), raw); // Step 2: parse the body so the canonical JSON can be signed and compared. const event = JSON.parse(raw); // Step 3: X-Signature-V2 is the recommended signature. Check each V2 header on its own. const canonical = canonicalJson(event); const v2Ok = matchesAny(req.header('X-Signature-V2'), canonical) || matchesAny(req.header('X-Signature-V2-Previous'), canonical); // The webhook is authentic when either supported signature matches. if (!rawOk && !v2Ok) return res.sendStatus(401); // Acknowledge first. Delivery retries, so the write below must be idempotent. res.sendStatus(200); if (event.webhook_type === 'status.updated') { saveStatus(event.event_id, event.vendor_data, event.status).catch((err) => { console.error('status_persist_failed', event.event_id, err.message); }); } } module.exports = { diditWebhook }; - Guard the protected handler with the recorded status. The guard reads what the webhook wrote. Nothing in the request path decides on its own.
// guard.js const { getStatus } = require('./store'); async function requireApprovedUser(req, res, next) { const status = await getStatus(req.user.id); if (status !== 'Approved') { return res.status(403).json({ error: 'verification_required' }); } next(); } module.exports = { requireApprovedUser }; - Reconcile with the decision endpoint. If the webhook never arrives, or you need the full feature data, read the decision yourself and branch on
session_kind.async function readDecision(sessionId) { const response = await fetch( 'https://verification.didit.me/v3/session/' + sessionId + '/decision/', { headers: { 'x-api-key': process.env.DIDIT_API_KEY } } ); if (!response.ok) throw new Error('decision_read_failed ' + response.status); const decision = await response.json(); if (decision.session_kind === 'business') return handleBusiness(decision); return decision.status; // Approved, Declined, In Review, Expired, ... }

Expected output
On the first call your client receives the verification URL. The 202 body below is an example application response written by this middleware. It is not a Didit API response contract; the Didit response to POST /v3/session/ carries the session id and the hosted URL in its own schema.
HTTP/1.1 202 Accepted
{
"status": "verification_required",
"url": "https://verify.didit.me/session/3FaJ9wLqX2Mz"
}
When the user finishes, Didit posts a signed event to your webhook. The envelope carries the status, your own identifier and, for Approved, Declined, In Review and Abandoned, the decision object.
{
"event_id": "7c1f...",
"session_id": "3fa2...",
"status": "Approved",
"webhook_type": "status.updated",
"timestamp": 1627680000,
"environment": "live",
"workflow_id": "9b44...",
"workflow_version": 1,
"vendor_data": "user-42",
"metadata": { "route": "/api/withdraw", "amount": 2500 },
"decision": { "...": "full feature data" }
}
The decision object mirrors GET /v3/session/{session_id}/decision/, with per-feature arrays such as id_verifications, liveness_checks, face_matches and aml_screenings. Status strings are exact and case sensitive, and Kyc Expired uses a single capital K. The full list is in Verification statuses.

Inputs and outputs
| Field | Direction | What it does |
|---|---|---|
workflow_id | Request, required | Stable workflow UUID. KYC workflows create user sessions, KYB workflows create business sessions. |
vendor_data | Request, recommended | Your stable user or business identifier. Binds the session to an entity and drives duplicate detection. |
callback | Request, optional | Where the browser returns when the flow finishes. Must be on one of the application allowed domains, or creation fails with 400. A callback hit is user-controlled and never proof of approval. |
metadata | Request, optional | Arbitrary JSON echoed back in responses and webhooks. Never shown to the user. |
session_expiration_time | Request, optional | Seconds the link stays valid, between 3600 and 2419200, overriding the workflow setting for this session. |
session_id | Response and webhook | Identifier you pass to the decision endpoint. |
url | Response | Hosted verification URL. Send the user there, or hand it to the JavaScript SDK or iframe. |
status | Webhook and decision | Not Started, In Progress, Approved, Declined, In Review, Awaiting User, Resubmitted, Expired, Abandoned, Kyc Expired. |
session_kind | Decision | user or business. Always branch on it before reading feature arrays. |
Failure cases and recovery
| Symptom | Meaning | Recovery |
|---|---|---|
401 from verification.didit.me | The x-api-key is wrong, malformed, revoked or expired | Fetch the key again from Developers, then API keys, or use the recover-key flow in the auth docs |
| 403 with a valid looking key | No key header, a scoped key without access to this resource, or a call from an address outside its IP list | Use a key that holds the privilege, and check the IP list |
429 with a wait field | Rate limit | Read wait from the response body, back off for that many seconds, then retry |
400 on callback | The URL is not on the application allowed domains | Add the origin to the allowed domains or use an allowed scheme, for example a custom app deep link |
| 404 on a session route | The session is outside the scoped key workflows, or belongs to another application | Read it with a key that covers that workflow |
| 403 on the decision endpoint | The key lacks read:sessions | Read with a key that has that privilege |
| Webhook returns 401 in your logs | Stale timestamp over 300 seconds, a signature computed over re-encoded JSON, or a rotated secret | Check clock skew, hash the canonical JSON for X-Signature-V2, and accept X-Signature-V2-Previous during rotation |
| Status sits at In Progress, Abandoned or Expired | The user never finished, or the link timed out | Create a new session for the same vendor_data and send a fresh link |
Three practical notes. If your stack re-encodes JSON bodies, X-Signature-V2 over canonical JSON is the reliable choice; X-Signature over the exact raw bytes only works when nothing rewrites the body. After a destination secret is rotated, the current and the previous signature both arrive for 24 hours, so accept a match on either. Acknowledge with 2xx first and write state idempotently, because delivery retries and the same event_id can arrive more than once.
What you pay for, and where a person decides
Billing is per completed check, drawn from prepaid credit. Posting to /v3/session/ is not the billable event. The checks inside the workflow are. The prices your middleware can route to, from the live feed:
- Full ID check (KYC) $0.33: ID document $0.15, passive liveness $0.10, face match 1:1 $0.05, device and IP analysis $0.03.
- AML screening $0.20 per check. Ongoing AML monitoring $0.07 per person per year.
- Email verification $0.02. US SMS code $0.0473, which is the carrier price plus Didit $0.02.
- Active liveness $0.15. NFC chip reading $0.15 as an add-on. Proof of address $0.20. Age estimation $0.10.
- Business verification from $2.00 per company, plus $0.20 per person AML and a linked full ID check per owner or officer.
- Workflow Orchestrator, Reusable KYC, SDKs and the MCP server are free.
The review boundary matters more than the price. In Review means automated checks raised warnings and a person has to decide, so your guard must treat it exactly like not approved. Approval, decline and resubmission are decisions a reviewer takes in the console, and a reviewer can move a Declined session to Resubmitted after the user fixes something. The Express middleware is never the place to overrule a warning.
Approved means every check passed. In Review means a human still has to look. Route those two states to different code paths and the rest of the enforcement stays simple.

Worked cost example
Take 10,000 verification-gated requests a month on the light and heavy pair. Your rule sends 9,000 to the light workflow and 1,000 to the heavy workflow. The light figure assumes one completed email verification and one completed US SMS code per user. The heavy figure assumes one completed full ID check plus one AML screening.
| Bucket | Sessions | Unit price | Line total |
|---|---|---|---|
| Light: email $0.02 + US SMS $0.0473 | 9,000 | $0.0673 | $605.70 |
| Heavy: full ID check $0.33 + AML $0.20 | 1,000 | $0.53 | $530.00 |
| Total | 10,000 | $1,135.70 |
The arithmetic: 9,000 times 0.0673 equals 605.70. 1,000 times 0.53 equals 530.00. 605.70 plus 530.00 equals 1,135.70. The full ID check breaks down as 0.15 plus 0.10 plus 0.05 plus 0.03 equals 0.33.
Nothing in the list above charges for the middleware, the workflow logic or the webhook. Sandbox runs are free and mocked, so development months cost $0. On paid plans the Free plan adds $10 of monthly credit for eligible organizations, Growth is $99 a month with $115 of credit and 4 percent off every Didit price, and Scale is $299 a month with $350 of credit and 10 percent off. Plan credit does not roll over, and top-ups last 12 months. Check didit.me/pricing before you commit a number to a budget.
To change the user experience without touching the middleware, switch the front end only. The web SDK overview covers the JavaScript SDK, the iframe and the redirect method, and all three still deliver the final decision by signed webhook.
Sources
- Didit pricing page, prices read from the live price feed on November 26, 2026.
- Didit pricing docs: billing rules and standalone API prices.
- Didit API authentication: key handling, hosts, 401 and 403 behavior.
- Create Session API: request fields and the callback rules.
- Retrieve Session API: decision payload and
session_kind. - Didit webhooks: signature headers, canonical JSON, retries, event types.
- Didit verification statuses: the exact status strings.
- Didit web SDK overview: JavaScript SDK, iframe and redirect.
- Didit product facts and Didit MCP server.
Next step: open the sandbox at https://business.didit.me/, create the two workflows, and run the middleware against mocked checks. No sales call, and nothing above costs anything until you switch to a live key.
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
Alberto Rosas
Co-founder and CEO

Questions
Frequently asked questions
How do I add identity verification to an Express.js app?
Create a verification session server side with POST https://verification.didit.me/v3/session/ and the x-api-key header, then send the user to the returned URL. Record the decision when Didit posts a signed status.updated webhook to your endpoint. Gate the protected route on that recorded status, never on the browser redirect.
Can an Express middleware return a verified user in the same request?
No. Identity verification needs the user to complete steps in a browser or device, so the first response can only start the process. Your middleware returns a verification URL with a 202 status, and the approved or declined outcome arrives later by webhook. Any code that assumes a synchronous result will either block or fake a decision.
How do I pick a different Didit workflow for each request?
Keep two or more published workflows in the Business Console and store their workflow_id UUIDs as environment variables. Your middleware picks one from request context such as transaction amount, country or user history, then passes it as workflow_id on session creation. Adding or removing steps happens in the console, so the code keeps calling the same id.
Which Didit endpoint creates a verification session?
POST https://verification.didit.me/v3/session/ creates sessions for both user (KYC) and business (KYB) workflows, and the workflow type decides which kind you get. The body needs workflow_id, and vendor_data is strongly recommended because it binds the session to your entity. The response contains the session id and the hosted URL.
How do I verify a Didit webhook signature in Node.js?
Mount the webhook route on express.raw({ type: 'application/json' }) before express.json(), so the handler sees the bytes Didit sent. Reject anything whose X-Timestamp is more than 300 seconds from now, then compare signatures with constant-time checks: X-Signature or X-Signature-Previous over the raw bytes, and X-Signature-V2 or X-Signature-V2-Previous over the sorted canonical JSON of the parsed event. Accept a match on either supported signature, check each V2 header on its own, and take the previous-secret headers into account for 24 hours after a secret rotation. Answer 2xx first, then persist the status idempotently with its event_id.
What do Didit session statuses mean for my middleware?
Approved means every check passed and you can grant access. Declined means at least one check failed, and In Review means a person still has to decide, so treat it as not approved. Expired and Abandoned mean the user never finished in time, and Kyc Expired means a previously approved document has since passed its expiry date.
What if the Didit webhook never arrives?
Read the source of truth yourself with GET https://verification.didit.me/v3/session/{session_id}/decision/ and branch on session_kind before reading feature arrays. That call needs a key with read:sessions. Reconciliation is also the correct pattern when you verify with the deprecated X-Signature-Simple header, which authenticates the envelope but not the decision body.
How much does dynamic identity verification cost per user?
A light workflow with one completed email verification and one completed US SMS code is $0.0673, which is $0.02 plus $0.0473. A heavy workflow with a full ID check and AML screening is $0.53, which is $0.33 plus $0.20. Billing is per completed check from prepaid credit, and sandbox checks are free.
Can I test this for free before paying?
Yes. The sandbox is free on every plan and every check in it is mocked, so an integration can be built and tested end to end without spending credit. New sandbox keys start with sk_test_ and new live keys with sk_live_; older keys may have no prefix and still work. You switch the environment variable when you are ready to go live.
Does the middleware work with the hosted flow, an iframe or the JavaScript SDK?
All three start from the same session URL. Return it as JSON and redirect, or hand it to the JavaScript SDK or an iframe on your page. The final decision still arrives by signed webhook in every case, so the middleware code does not change when you switch presentation.
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


