Express.js Middleware for Dynamic Identity Verification
Learn how to build an Express.js middleware to implement dynamic identity verification decisions using Didit's powerful API. This approach allows for flexible, real-time risk assessment and tailored user experiences, enhancing.

Dynamic Verification with Express.jsImplement an Express.js middleware to orchestrate real-time identity verification decisions, adapting workflows based on user context or transaction risk using Didit's API.
Leverage Didit's Modular ArchitectureDidit's open, modular identity platform allows developers to easily integrate specific verification checks like ID Verification, Liveness, and AML Screening into their middleware.
Automate Trust with AI-Native SolutionsUtilize Didit's AI-native capabilities for intelligent decision-making, reducing manual review and streamlining compliance processes for a more efficient and secure system.
Seamless Integration and Free Core KYCDidit offers a developer-first approach with clean APIs, an instant sandbox, and Free Core KYC, making it easy to build and deploy sophisticated verification logic within your Express.js applications.
The Need for Dynamic Identity Verification
In today's digital landscape, static identity verification processes are no longer sufficient. Businesses need the flexibility to adapt their KYC (Know Your Customer) and AML (Anti-Money Laundering) requirements based on various factors, such as user location, transaction value, risk profile, or even the specific service being accessed. For instance, a low-value transaction might only require basic email verification, while a high-value financial operation demands a full ID document scan, liveness check, and AML screening. Building an Express.js middleware provides an elegant and efficient way to embed these dynamic decision-making capabilities directly into your application's request-response cycle.
This dynamic approach allows for a more friction-aware user experience. Instead of subjecting every user to the most stringent verification process, you can tailor the journey, asking for more information only when necessary. This not only improves conversion rates but also enhances security by focusing resources where they are most needed. Implementing this requires a robust identity verification platform, and Didit, with its modular and API-first design, is perfectly suited for such an integration.
Designing Your Express.js Verification Middleware
An Express.js middleware function has access to the request and response objects, and the next middleware function in the application’s request-response cycle. This makes it an ideal place to intercept requests, perform identity checks, and modify the flow based on the results. Here’s a conceptual outline of how such a middleware could work:
- Intercept Request: The middleware catches an incoming request to a protected route (e.g., a route for initiating a high-value transaction).
- Extract Context: It extracts relevant information from the request, such as the user ID, IP address, requested action, or transaction amount.
- Evaluate Risk/Policy: Based on this context, the middleware determines the required level of verification. This could involve checking internal user profiles, real-time risk scores, or predefined business rules.
- Initiate Didit Session: If verification is needed, the middleware makes an API call to Didit to create a new verification session. Didit's
didit_create_sessiontool is perfect for this, allowing you to specify aworkflow_idthat corresponds to the desired verification steps (e.g., ID Verification, Passive & Active Liveness, AML Screening). - Redirect or Embed: Didit returns a unique verification URL. The middleware can then redirect the user to this URL, or, for a more integrated experience, embed the Didit verification flow within an iframe on your site.
- Handle Webhook Callbacks: Didit's platform sends real-time updates via webhooks as the user progresses through verification and when the final decision is made. Your backend needs a separate endpoint to receive and process these webhooks, updating the user's verification status in your database.
- Permit or Deny Access: Once the webhook confirms successful verification, the user can be granted access to the protected resource. If verification fails, access is denied.
This dynamic orchestration allows you to define complex verification journeys without hardcoding every decision into your application logic. Didit's modular architecture means you can easily swap out or add new verification steps (e.g., Proof of Address or Age Estimation) to your workflows in the Business Console without changing your application code.
Practical Implementation with Didit's API
Let's consider a simplified example of an Express.js middleware that initiates a Didit verification session. First, ensure you have an API key from Didit. You'll use this to authenticate your requests.
const express = require('express');
const axios = require('axios');
const app = express();
// Replace with your actual Didit API Key and Workflow ID
const DIDIT_API_KEY = 'YOUR_DIDIT_API_KEY';
const HIGH_RISK_WORKFLOW_ID = 'YOUR_HIGH_RISK_WORKFLOW_ID'; // e.g., ID + Liveness + AML
const LOW_RISK_WORKFLOW_ID = 'YOUR_LOW_RISK_WORKFLOW_ID'; // e.g., Email + Phone
// Mock function to determine risk based on user data
const assessRisk = (userId, transactionAmount) => {
// In a real application, this would involve more sophisticated logic
if (transactionAmount > 1000 || userId === 'high_risk_user_id') {
return 'HIGH';
}
return 'LOW';
};
const dynamicVerificationMiddleware = async (req, res, next) => {
const userId = req.user.id; // Assuming user ID is available from session/auth
const transactionAmount = req.body.amount; // Assuming amount is in request body
const riskLevel = assessRisk(userId, transactionAmount);
let workflowIdToUse;
if (riskLevel === 'HIGH') {
console.log(`User ${userId} identified as HIGH risk. Initiating high-risk verification.`);
workflowIdToUse = HIGH_RISK_WORKFLOW_ID;
} else {
console.log(`User ${userId} identified as LOW risk. Initiating low-risk verification.`);
workflowIdToUse = LOW_RISK_WORKFLOW_ID;
}
try {
const response = await axios.post(
'https://verification.didit.me/v3/session/',
{
workflow_id: workflowIdToUse,
vendor_data: userId, // Link session to your internal user ID
callback: 'https://your-app.com/didit/webhook-handler' // Your webhook endpoint
},
{
headers: {
'x-api-key': DIDIT_API_KEY,
'Content-Type': 'application/json'
}
}
);
const verificationUrl = response.data.url;
console.log(`Verification URL for user ${userId}: ${verificationUrl}`);
// Redirect the user to Didit's hosted verification page
return res.redirect(verificationUrl);
// Alternatively, send the URL back to the client for frontend integration (e.g., iframe)
// return res.status(402).json({ message: 'Verification required', verificationUrl });
} catch (error) {
console.error('Error creating Didit session:', error.response ? error.response.data : error.message);
return res.status(500).send('Verification service unavailable.');
}
};
// Example protected route
app.post('/api/perform-transaction', dynamicVerificationMiddleware, (req, res) => {
// This code will only execute if dynamicVerificationMiddleware allows it (e.g., after a webhook confirms verification)
res.send('Transaction successful!');
});
app.listen(3000, () => console.log('Server running on port 3000'));
This example demonstrates how to dynamically select a Didit workflow based on risk assessment and initiate a session. Remember, the actual decision to proceed with the transaction should be made after Didit's webhook confirms the verification result.
How Didit Helps
Didit is uniquely positioned to empower developers to build dynamic identity verification solutions. Our AI-native, developer-first platform provides the building blocks you need:
- Modular Identity: Didit's open and modular architecture allows you to compose verification workflows with specific checks like ID Verification (OCR, MRZ, barcodes), Passive & Active Liveness, 1:1 Face Match, AML Screening & Monitoring, Proof of Address, and Age Estimation. You combine these into custom workflows in our no-code Business Console, each with a unique
workflow_idthat your middleware can dynamically call. - Orchestrated Workflows: Define complex verification journeys with conditional logic and multiple steps, all managed by Didit, reducing the burden on your application.
- Developer-First Experience: With clean APIs, an instant sandbox, and comprehensive documentation, integrating Didit into your Express.js application is straightforward. You can generate verification links via a simple API call, as demonstrated above.
- Automation Over Manual Review: Didit's AI-native capabilities automate decision-making for a high percentage of verifications, significantly reducing the need for manual review and speeding up the onboarding process.
- Free Core KYC: Get started with essential identity verification features without upfront costs, allowing you to test and scale your dynamic verification strategies effectively.
Whether you need to verify age for an app, ensure compliance for financial services, or prevent fraud with advanced biometrics, Didit's comprehensive suite of products and flexible integration options make it the ideal partner for building dynamic and robust identity verification into your Express.js applications.
Ready to Get Started?
Ready to see Didit in action? Get a free demo today.
Start verifying identities for free with Didit's free tier.