Skip to main content

Express.js Middleware for Adaptive Friction in Identity Verification

Implement adaptive friction in your Express.js applications for smarter identity verification. This approach dynamically adjusts security based on risk signals, enhancing user experience while preventing fraud.

Express.js Middleware for Adaptive Friction in Identity Verification

Contents

In this guide

Jump to the part you need.

Dynamic Security ImplementationAdaptive friction uses real-time risk assessment to apply varying levels of verification, ensuring a smoother user experience for trusted users and stronger checks for suspicious activities.

Express.js Middleware for IntegrationA custom Express.js middleware can effectively intercept requests, evaluate risk, and trigger appropriate identity verification flows via Didit's API, streamlining integration into existing applications.

Leveraging Didit's Modular PlatformDidit offers a modular, AI-native identity platform with products like ID Verification, Liveness, and AML Screening, which can be orchestrated to create flexible verification workflows tailored to risk levels.

Automated Trust and Fraud PreventionBy integrating Didit, developers can automate complex identity checks, reduce manual review, and enhance fraud prevention with a developer-first approach, including core KYC and no setup fees.

The Need for Adaptive Friction in Identity Verification

In today's digital landscape, balancing user experience with robust security is paramount. Traditional identity verification often applies a one-size-fits-all approach, which can introduce unnecessary friction for legitimate users or, conversely, be insufficient for high-risk scenarios. This is where adaptive friction comes in. Adaptive friction is a dynamic security strategy that adjusts the level of verification required based on real-time risk assessment. For instance, a user logging in from a familiar device and location might experience a seamless, single-factor authentication, while a user attempting to access sensitive information from a new, suspicious IP address could be prompted for a multi-factor authentication or a full identity document scan.

The goal is to minimize user inconvenience while maximizing security effectiveness. Implementing adaptive friction requires a sophisticated system that can analyze various signals—such as IP address, device fingerprint, transaction history, and behavioral biometrics—to determine the appropriate level of scrutiny. For developers working with Node.js and Express.js, building this intelligence into their applications can significantly enhance both security posture and user satisfaction.

Designing Your Adaptive Friction Middleware

An Express.js middleware is an ideal place to implement adaptive friction logic. Middleware functions have access to the request and response objects, allowing them to perform tasks like risk assessment, modify request/response cycles, or terminate the request early. Here's a conceptual outline of how such a middleware might function:

  1. Request Interception: The middleware intercepts incoming requests to protected routes.
  2. Risk Assessment: It gathers relevant data points (e.g., IP address, user agent, session history, perhaps even a preliminary check against a fraud database).
  3. Risk Scoring: Based on these data points, a risk score is calculated. This could be simple (low, medium, high) or more granular.
  4. Conditional Verification: Depending on the risk score, the middleware decides whether to proceed with the request, trigger additional verification steps, or block the request entirely.
  5. Integration with Identity Platform: For additional verification, the middleware interacts with an identity verification platform like Didit to initiate checks such as ID Verification, Passive & Active Liveness, or AML Screening.

This modular approach ensures that your core application logic remains clean, while security concerns are handled effectively and centrally.

Building the Express.js Middleware: A Practical Example

Let's consider a simplified Express.js middleware that integrates with Didit to apply adaptive friction. We'll assume a basic risk assessment function that returns a risk level.


const express = require('express');
const axios = require('axios'); // For making HTTP requests to Didit

const DIDIT_API_KEY = 'YOUR_DIDIT_API_KEY';
const DIDIT_VERIFICATION_URL = 'https://verification.didit.me/v3/session/';

// Placeholder for a more sophisticated risk assessment function
function assessRisk(req) {
    // In a real-world scenario, this would involve checking IP, device, user history, etc.
    const ipAddress = req.ip;
    if (ipAddress === '192.168.1.100') { // Example: known suspicious IP
        return 'HIGH';
    } else if (req.headers['user-agent'].includes('bot')) {
        return 'MEDIUM';
    } else {
        return 'LOW';
    }
}

const adaptiveFrictionMiddleware = async (req, res, next) => {
    const riskLevel = assessRisk(req);
    console.log(`Request from IP: ${req.ip}, Risk Level: ${riskLevel}`);

    if (riskLevel === 'HIGH') {
        // For high risk, initiate a full ID verification and liveness check
        try {
            const workflowId = 'YOUR_HIGH_RISK_WORKFLOW_ID'; // Pre-configured in Didit console
            const response = await axios.post(DIDIT_VERIFICATION_URL, {
                workflow_id: workflowId,
                vendor_data: req.user ? req.user.id : 'anonymous_high_risk',
                callback: 'https://your-app.com/didit-webhook'
            }, {
                headers: {
                    'x-api-key': DIDIT_API_KEY,
                    'Content-Type': 'application/json'
                }
            });

            const { url: verificationUrl, session_id: sessionId } = response.data;
            // Redirect user to Didit's hosted verification page
            return res.status(403).json({
                message: 'High risk detected. Please complete identity verification.',
                verificationUrl: verificationUrl,
                sessionId: sessionId
            });
        } catch (error) {
            console.error('Error initiating Didit verification:', error.response ? error.response.data : error.message);
            return res.status(500).send('Verification service unavailable.');
        }
    } else if (riskLevel === 'MEDIUM') {
        // For medium risk, perhaps a simpler check or additional MFA
        // This could involve triggering a Didit Phone & Email Verification or a custom challenge
        console.log('Medium risk detected. Consider additional MFA or light verification.');
        // For this example, we'll just log and proceed, but in production, you'd add a step.
        next();
    } else {
        // Low risk, proceed as normal
        next();
    }
};

// Example usage:
const app = express();
app.use(express.json());

app.get('/protected-resource', adaptiveFrictionMiddleware, (req, res) => {
    res.send('Access granted to protected resource!');
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

This example demonstrates how the middleware can make a real-time decision and, for high-risk scenarios, initiate a session with Didit's API for a comprehensive identity check. The user would then be redirected to Didit's hosted verification flow. Didit's Verification Links and Unilinks are perfect for this, allowing you to launch complete identity verification flows without extensive frontend development.

Integrating Didit for Comprehensive Verification Workflows

Didit's platform is built to facilitate adaptive friction. With its open, modular architecture, you can define sophisticated workflows in the Business Console that combine various identity checks. For a high-risk scenario, your workflow might include:

  • ID Verification: Utilizing OCR, MRZ, and barcode scanning for document authenticity.
  • Passive & Active Liveness: To detect deepfakes and ensure the user is a real, present person.
  • 1:1 Face Match: Comparing the selfie to the document photo.
  • AML Screening & Monitoring: Checking against watchlists for compliance.
  • Proof of Address: Verifying the user's residential address.

For lower-risk situations, a simpler workflow might only require Phone & Email Verification. The beauty of Didit is the ability to orchestrate these checks dynamically through a no-code engine or via clean APIs, giving you ultimate control over your adaptive friction strategy.

How Didit Helps

Didit is the AI-native, developer-first identity platform designed to make implementing adaptive friction seamless and powerful. Our modular architecture allows you to compose verification flows tailored to any risk level. With Didit's core KYC, you can get started, and our pay-per-successful-check model ensures you only pay for what you use, with no upfront costs or setup fees. The AI-native approach means our systems are constantly learning and improving, providing superior fraud detection and accuracy.

Didit's comprehensive suite of products, including ID Verification (OCR, MRZ, barcodes), Passive & Active Liveness, 1:1 Face Match, AML Screening & Monitoring, Proof of Address, Age Estimation, Phone & Email Verification, and NFC Verification, provides all the building blocks you need. You can design complex workflows through our no-code Business Console or integrate directly using our clean APIs, empowering your Express.js middleware to trigger the exact level of verification required for each unique user interaction. This automation reduces manual review, speeds up onboarding, and significantly bolsters your fraud prevention capabilities.

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.

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

Alberto Rosas

Co-founder and CEO

Alberto Rosas

Alberto Rosas

Co-founder and CEO

About Didit

Questions

Blog questions

Who writes the Didit blog?
The Didit team. Guides reviewed by Alberto Rosas, co-founder and CEO, carry his byline. The rest are published as Didit.
Which topics does the blog cover?
Eight topics: ID verification, business verification (KYB), AML, sanctions and compliance, fraud prevention, transaction monitoring and crypto, country guides, agents and developers, and product updates.
Is the blog available in my language?
Yes, in 15 languages: English, Spanish, French, German, Brazilian and European Portuguese, Catalan, Russian, Arabic, Chinese, Japanese, Hindi, Indonesian, Korean and Swahili. Not every post is translated, so each language shows the posts it has.
Where do I find product updates?
In the changelog at /changelog/ and under the Product updates topic.
Are these posts legal advice?
No. Regulation posts explain rules; your legal team decides how they apply.
How do I find posts on one topic?
Open one of the eight topics, or search the blog.
Are posts dated?
Yes. Every post shows when it was published and when it was last updated.
Do posts link to the docs?
Developer posts link to the matching page on docs.didit.me and to the API reference.
Is the blog the same as the docs?
No. The blog explains rules, markets and product changes for a general reader, while docs.didit.me holds the integration guides and the API reference. Developer posts link the matching docs page and the API reference they describe.

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.