Skip to main content

Identity Verification in Next.js on Vercel: 2026 Integration Guide

Add hosted KYC to Next.js on Vercel with a server route and a signed webhook. A full KYC check costs $0.33 at list price. Test in our free sandbox and keep the API key on your server.

Identity Verification in Next.js on Vercel: 2026 Integration Guide

Contents

In this guide

Jump to the part you need.

This guide is for developers shipping a Next.js app on Vercel who need identity verification at signup. You add two server routes: one creates a Didit session, one receives the decision webhook. A full KYC check costs $0.33 at list price and the sandbox is free on every plan. The caveat is authorization: the API key stays server-side, and the user being verified must come from your own authenticated session, never from the request body.

Last updated: November 26, 2026. Prices checked against the live Didit price feed on November 26, 2026.

Didit plus Next.js on Vercel, at a glance
ItemDetail
What you buildTwo route handlers: app/api/kyc/session/route.ts and app/api/webhooks/didit/route.ts
Didit line usedUser Verification (KYC) through our verification API
API hosthttps://verification.didit.me
Authenticationx-api-key header carrying an application key, server side only
Create a sessionPOST /v3/session/ returns session_id, url and session_token
Read the decisionGET /v3/session/{session_id}/decision/, authenticated with the same key
Webhook securityHMAC-SHA256 over the raw request bytes, X-Timestamp within 300 seconds, X-Signature and X-Signature-Previous both accepted
PriceFull KYC $0.33 per completed check. Free plan: $10.00 of monthly credit for the first eligible Free organization created with a work email on a company domain. Sandbox is free and unlimited
What you need for the first sessionOne published workflow, one API key, one route handler
Ongoing costCompleted checks draw from prepaid credit. Standalone verification APIs have their own published rates

What the integration produces

When the work is done, a signed-in user clicks a button, your server creates a session, and the browser goes to the Didit hosted flow. The user photographs a document and takes a selfie. We decide, your webhook route receives a status.updated event, and your app marks that user verified. The redirect back to your callback page is not a decision: query parameters are browser input, so they can drive what you display and nothing more. The change that grants access comes from a verified webhook or from an authenticated decision fetch on the server.

A walkthrough of the screens a user sees during a Didit KYC verification
The hosted flow your Next.js user lands on after POST /v3/session/ returns a url.

The API for identity verification, used from Next.js

Our docs do not list a dedicated Next.js or Vercel connector. This guide uses our REST API and webhooks.

We use separate hosts for verification and account management. For the two handlers in this guide, call our verification API. https://verification.didit.me takes the application key in the x-api-key header on the session, decision and webhook-destination requests shown here. The account host https://apx.didit.me uses a Bearer JWT for account and application management, including login, organization and application administration, and API key recovery. Our verification API does not use OAuth Bearer tokens, so do not copy Bearer examples from other vendors into these routes.

A session is created from a published workflow. The workflow decides which checks run: ID document verification, passive or active liveness, face match 1:1, AML screening, proof of address, phone and email verification, and the rest of the modules on our public price list. We serve 4,000+ companies and support identity verification in 220+ countries and territories. Our inference latency is under 2 seconds at p99. The create call returns a hosted URL, and the callback you pass is where the browser returns with ?verificationSessionId={session_id}&status={status} appended.

Prerequisites

What you need before the first request
RequirementDetail
Didit planThe Free plan works. Its $10.00 of monthly credit goes to the first organization created on the Free plan with an eligible work email on a company domain. Sandbox testing is free and unlimited on every plan.
Didit workflowOne published KYC workflow, either from the KYC template or built step by step. Save its workflow_id UUID.
API keyBusiness Console, Developers, API keys. Newly issued live keys start with sk_live_ and sandbox keys with sk_test_; older keys with no prefix remain valid, so never validate a key by its prefix.
Key permissionThe decision endpoint needs a key holding the read:sessions privilege. A key without it returns 403.
Next.js clientA Next.js app deployed on Vercel with server route handlers. Any Node runtime route can call the API with fetch.
Callback URLA page on your Vercel domain that works in the user's browser. If your application has allowed domains configured, the callback must match one of those origins exactly, scheme, host and port included, or session creation fails with 400.
Webhook destinationA route on your Vercel domain that accepts POST requests from Didit's infrastructure. It does not need to be the same origin as the callback.
Environment variablesDIDIT_API_KEY, DIDIT_WORKFLOW_ID and DIDIT_WEBHOOK_SECRET, set in Vercel under Project Settings, Environment Variables. Never prefix them with NEXT_PUBLIC_.

Six steps to a working integration

  1. Create the organization and the workflow. Sign in at business.didit.me and create your Organization. Go to Workflows in the sidebar and click New workflow. Pick Verifying users, then either Describe it, Start from a template and choose KYC, or Start empty. A Simple workflow runs its steps in a fixed order; a node-based workflow branches on results. Publish it and copy the workflow UUID.

  2. Copy the API key. Choose the Application in the dropdown at the top, open Developers, then API keys. The Primary key is the application's own secret and has full access to the application. Create a separate key when a service or partner needs its own secret, because a scoped key carries only the privileges assigned to it. Store the value as DIDIT_API_KEY in Vercel Project Settings, Environment Variables. A key that reaches the browser bundle exposes its assigned privileges, and a leaked primary key gives full access to your application's API.

  3. Create the session route, authenticated first. Add app/api/kyc/session/route.ts. Resolve the user from your app's authenticated server session, reject the request when there is no signed-in user, and pass that trusted id as vendor_data. Save the returned session_id against the user before you return the hosted URL, so the webhook has something to match.

    import { NextResponse } from "next/server";
    import { auth } from "@/lib/auth"; // your existing server session helper
    import { saveSessionForUser } from "@/lib/store"; // your existing store
    
    export async function POST() {
      const session = await auth();
      if (!session?.user?.id) {
        return NextResponse.json({ error: "unauthenticated" }, { status: 401 });
      }
    
      const response = await fetch("https://verification.didit.me/v3/session/", {
        method: "POST",
        headers: {
          "x-api-key": process.env.DIDIT_API_KEY as string,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          workflow_id: process.env.DIDIT_WORKFLOW_ID,
          vendor_data: session.user.id,
          callback: "https://your-app.vercel.app/kyc/return",
        }),
      });
    
      const created = await response.json();
      if (!response.ok) {
        return NextResponse.json({ error: created.detail }, { status: response.status });
      }
    
      await saveSessionForUser(session.user.id, created.session_id);
    
      return NextResponse.json({ url: created.url });
    }
  4. Send the browser to the hosted flow. On the client, call your route and redirect to the returned url. Didit sends the browser back to your callback with ?verificationSessionId=...&status=..., so a page at /kyc/return can show a message such as "we are finishing your check". Treat those parameters as display input only. The page must not grant access, because anyone can type that URL. If your application has allowed domains configured, the callback origin must be on that list, otherwise session creation fails with 400.

  5. Fetch the decision on the server. After a verified webhook, or when you need the current state, call GET https://verification.didit.me/v3/session/{session_id}/decision/ with the same key, using the session id you stored for the signed-in user. Branch on session_kind first: it is "user" or "business". Read feature results from the plural arrays id_verifications[], liveness_checks[], face_matches[] and aml_screenings[]. A feature that did not run is absent or null, never a placeholder.

  6. Register the webhook destination. Create it from your server or a terminal, with the label, the deployed route and the v3 envelope your handler expects. Save the returned secret_shared_key as DIDIT_WEBHOOK_SECRET.

    curl -X POST https://verification.didit.me/v3/webhook/destinations/ \
      -H "x-api-key: $DIDIT_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "label": "Production",
        "url": "https://your-app.vercel.app/api/webhooks/didit",
        "subscribed_events": ["status.updated", "data.updated"],
        "webhook_version": "v3"
      }'

    Then verify every delivery before you trust it. Our recommended header is X-Signature-V2, which signs sorted canonical JSON. The helper below checks X-Signature, the header computed over the exact raw bytes you already hold in a Next.js route, and it accepts X-Signature-Previous as well. It is signature verification only: no status is applied inside it.

    import { createHmac, timingSafeEqual } from "node:crypto";
    
    const HEX_64 = /^[0-9a-f]{64}$/i;
    
    function parseSignature(header: string | null): Buffer | null {
      if (!header || !HEX_64.test(header)) return null;
      return Buffer.from(header, "hex");
    }
    
    // Signature verification only. Dedupe and status updates happen in the route.
    export async function verifyDiditWebhook(request: Request) {
      const raw = Buffer.from(await request.arrayBuffer());
    
      const timestampHeader = request.headers.get("x-timestamp");
      if (!timestampHeader || !/^[0-9]+$/.test(timestampHeader)) {
        throw new Error("stale timestamp");
      }
      const timestamp = Number(timestampHeader);
      if (!Number.isSafeInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > 300) {
        throw new Error("stale timestamp");
      }
    
      const expected = createHmac("sha256", process.env.DIDIT_WEBHOOK_SECRET as string)
        .update(raw)
        .digest();
    
      const candidates = [
        parseSignature(request.headers.get("x-signature")),
        parseSignature(request.headers.get("x-signature-previous")),
      ].filter((value): value is Buffer => value !== null);
    
      if (!candidates.some((candidate) => timingSafeEqual(candidate, expected))) {
        throw new Error("bad signature");
      }
    
      return JSON.parse(raw.toString("utf8"));
    }

    Your route then does three things before it answers: it looks up event.event_id and skips the delivery if that id was already applied, it matches event.session_id to the user you saved in step 3, and it uses that verified status event to fetch the current decision for the session still bound to that user. Apply the result only if that session is still current when writing it, and make sure an older result cannot overwrite a newer one. Record the event ID and status update together in your existing store. Only after that does it return a 2xx. If your handler is slower than 5 seconds, or answers 5xx or 404, we retry twice, after about 1 and 4 minutes, then drop the delivery. You can resend it from the destination's delivery log.

Field and event mapping

Didit fields and events mapped to your Next.js app
Didit field or eventWhere it appearsWhat you do with it
session_idCreate-session response, decision, webhook envelopeStore it against the authenticated user so the webhook can match it back
urlCreate-session responseRedirect the browser to the hosted flow
vendor_dataYou send it; it comes back in the decision and the webhookThe join key back to your own user id
statusWebhook and decisionMatch the exact strings, for example "Approved", "Declined", "In Review", "Abandoned", "Kyc Expired"
session_kindDecision responseBranch first: "user" for KYC, "business" for KYB
id_verifications[], liveness_checks[], face_matches[]Decision object, webhook decisionStore per-check results. These are always plural arrays
aml_screenings[]Decision objectRead aml_screenings as a plural results array when AML ran. The field can be absent or null when it did not run
event_idWebhook envelopeDe-dupe key for retries and replays
webhook_typeWebhook envelopeSwitch on status.updated or data.updated; there is no wildcard subscription
X-Signature, X-Signature-Previous, X-TimestampWebhook headersVerify authenticity over the raw bytes and reject anything older than 300 seconds. The -Previous header is sent for 24 hours after a secret rotation
sandbox_scenario, environmentWebhook envelopeConfirms a test session and which scenario produced it

Status to action

Match the exact string, then apply the access decision below. Nothing else should grant or revoke access in this integration.

What each session status means for access in your Next.js app
StatusWhat it meansWhat your app does
"Approved"The current approval decision for the session. Read decision_trace.decided_by to see who made it. If a reviewer manually changed the status, status_override records when and what the automatic status wasMark that one user verified, store the decision data, and grant access while that session stays current
"In Review"Automated checks raised warnings that need a humanKeep the user pending with no access until a reviewer decides
"Declined"The session was declined by the checks or by a reviewerKeep the user unverified, notify them, and optionally request a resubmission. A current Declined or Resubmitted result removes any access that session granted
"Kyc Expired"A previously approved document passed its expiry dateRevoke or re-verify, because the earlier approval no longer holds

Test with sandbox data before you ship

Use the sandbox application key that starts with sk_test_. Sandbox checks are mocked. Use the documented scenarios and sample data to test without sending real personal information.

To make an outcome deterministic, pass sandbox_scenario on create with a slug from GET /v1/sandbox/scenarios/. You can also arm a scenario after create, while the session is still "Not Started", with POST /v3/session/{session_id}/sandbox/arm/. The slug comes back on the webhook as sandbox_scenario, and the envelope sets environment to sandbox.

The analysis screen a user sees after capturing an identity document
The document step inside the hosted flow. In the sandbox the same step returns a scripted result instead of a real check.

Acceptance check you can run. Create a workflow with OCR, passive liveness and face match, then run these three passes from a Vercel preview deployment:

  • An approval scenario: the webhook arrives with webhook_type of status.updated, status of "Approved" and a decision object carrying id_verifications[], liveness_checks[] and face_matches[]. Only the user bound to that session_id becomes verified, and the stored session id matches.
  • A decline scenario: a second test user with no prior approval stays unverified after the delivery, and the decline event matches that user's session.
  • A replay of the same event_id: the second delivery changes nothing, which proves the de-dupe step works.
A session overview in the Didit Business Console showing its warnings
The same session in our Business Console, where you check warnings while debugging a sandbox run.

Error codes and fixes

What each failure means in a Next.js route
SymptomCauseFix
401 on verification.didit.meThe x-api-key header is wrong, malformed, revoked or expiredRe-copy the key from Developers, API keys, and confirm you are not mixing a sandbox key into a live environment
403 with "You do not have permission to perform this action."No x-api-key header, a scoped key without access to this resource, or a key called from an address outside its IP listSend the header from a server route and use a key with the access the route needs
403 with "code": "application_deleted"The key's application was deletedDo not retry. Use a key of an application that exists
400 on session createInvalid workflow_id, or a callback that is not on the application's allowed domainsUse the published workflow UUID and a callback on an allowed origin
404 on a session routeThe session ID is unknown, the session falls outside the scoped key's workflows or statuses, or it belongs to another applicationCheck the stored session ID, the application and the key scope, then use a key whose limits include that session
429Rate limitThe response carries a wait field in seconds. Back off, then retry
Webhook delivery failsThe handler answered 5xx or 404, or took longer than 5 secondsOpen the destination delivery log, fix the handler, resend. Meanwhile read the decision endpoint
Signature mismatch on every deliveryThe body was decoded to text and re-encoded before hashing, or the wrong secret or header was usedRead the body as bytes with Buffer.from(await request.arrayBuffer()), hash exactly those bytes, and accept X-Signature or X-Signature-Previous during a rotation
A delivery accepted with a malformed headerA nonnumeric X-Timestamp became NaN and slipped past the freshness check, or a short signature string reached the comparisonRequire a decimal integer that fits a safe integer and differs from server time by at most 300 seconds, and require each signature to be exactly 64 hex characters before decoding to 32 bytes

Production cutover, rotation and disconnecting

  • Go live. Publish the live workflow and note its UUID, deploy the live sk_live_ key, create a live webhook destination with its own signing secret, and set the live callback origin so it matches the allowed domains of the live application. Live and sandbox keys belong to different applications, so keep them in separate Vercel environments.
  • Rotate a key. Create a new key under Developers, API keys, deploy it as DIDIT_API_KEY in Vercel, confirm sessions still create, then revoke the old key.
  • Rotate the webhook secret. Compare the computed digest against X-Signature and, when present, X-Signature-Previous, and accept a match on either. Destination webhooks include the previous header for 24 hours after rotation, so an instance still running the old secret keeps accepting deliveries while you deploy the new one.
  • Disconnect this integration. Remove its webhook destination and revoke the API key this deployment uses.

If you are moving an existing flow over from a previous provider, our migration path is described at didit.me/switch.

What it costs on both ends

Didit list prices for a Next.js KYC integration, November 26, 2026
ItemPriceUnit
Full ID check (KYC): ID document, passive liveness, face match 1:1, device and IP analysis$0.33completed check
ID Verification alone$0.15check
Passive Liveness$0.10check
Face Match 1:1$0.05check
Device and IP Analysis$0.03check
Face Search 1:N$0.05search
AML Screening$0.20check
Proof of Address$0.20check
Workflow Orchestrator, Reusable KYC, MCP serverFreeincluded
Sandbox testingFreeunlimited

On the Vercel side, this integration adds one handler invocation per session creation request, one per webhook delivery, and one additional server-side Didit API request whenever your app fetches a decision. The volume follows your signups rather than your page views. Nothing in our routes needs a new database: your existing store holds the session id and the status.

In this hosted workflow, completed checks draw from prepaid credit. The decision endpoint retrieves an existing result. This estimate covers the completed KYC and AML checks shown below. Standalone verification APIs have their own published rates. On the Free plan, unused monthly credit expires at the end of the plan month, and credit does not cover phone verification codes.

Worked example: 1,000 signups a month

Take 1,000 new users a month, each running the full KYC check, with 200 of them also screened for AML.

  • KYC: 1,000 x $0.33 = $330.00
  • AML screening: 200 x $0.20 = $40.00
  • Total at list price: $330.00 + $40.00 = $370.00 a month
  • Free plan credit: 30 completed checks at $0.33 cost $9.90, which leaves $0.10 of the $10.00 monthly credit
  • On Growth: 1,000 x $0.3168 = $316.80 and 200 x $0.192 = $38.40, so $355.20 of usage. Minus $115.00 of included credit, that is $240.20 of top-ups, plus the $99.00 monthly fee, for $339.20 in total. $240.20 comes from top-up credit. If you start with no top-up balance, the total cash cost is $339.20 for that month

Testing adds nothing: sandbox sessions are free on every plan. Billing is per completed check, and this estimate covers the completed KYC and AML checks above.

Building it with a coding agent instead

If you would rather have an assistant write the two routes, start with the Didit integration prompt, our public documentation that covers the SDK choice, HMAC verification, every status and decision parsing. We also run a hosted MCP server at https://mcp.didit.me/mcp, which is free and included in every plan, and Didit MCP setup explains how to connect a client to it.

Sources

Next step: create an organization at business.didit.me, build a KYC workflow, copy the sandbox key, and run one session from a Vercel preview deployment. There is no sales call and the sandbox is free. When you go live, $0.33 is the USD list price per completed full KYC check.

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

Frequently asked questions

Is there an API for identity verification that works with Next.js?

Yes. Our verification API is a REST API over HTTPS: you create a session with POST https://verification.didit.me/v3/session/ and authenticate with the x-api-key header. From Next.js you call it inside a route handler with fetch, which keeps the key on the server. There is no separate KYB endpoint; the workflow's type decides which kind of session is created.

Where should the Didit API key live in a Next.js app on Vercel?

In a Vercel environment variable named DIDIT_API_KEY, read only from server code such as a route handler or a server action. Never prefix it with NEXT_PUBLIC_, because that inlines the value into the browser bundle. A leaked key exposes the privileges assigned to it, and the primary key has full access to the application.

Do I need a database to use Didit with Next.js?

You need somewhere to store the session id and the status against your user, because the webhook can arrive after the browser has moved on. That can be the database you already have, and it does not have to run on Vercel. Every result is also readable from the decision endpoint, so a missed webhook never blocks a decision.

How do I redirect the user to the verification flow?

Take the url from the create-session response and send the browser there. We redirect back to the callback you passed, with ?verificationSessionId={session_id}&status={status} appended. If your application has allowed domains configured, the callback origin must be on that list or session creation fails with 400.

Can I mark the user verified when the callback redirect arrives?

No. Callback query parameters are browser input, so anyone can open that URL with any status. Use them to pick a message on the page. On the server, look up the session already bound to the signed-in user and mark that user verified only for an exact "Approved" status from a verified webhook or an authenticated decision fetch. Keep "In Review" pending.

How do I verify the Didit webhook signature in a Next.js route handler?

Read the body as bytes with Buffer.from(await request.arrayBuffer()) before any parsing, read X-Timestamp as a string, reject a missing value or one that fails /^[0-9]+$/, then convert it to a number and apply the safe-integer and absolute 300-second checks, and recompute the HMAC-SHA256 over exactly those bytes with the destination's secret_shared_key. Validate each candidate signature as exactly 64 hex characters, decode it to 32 bytes, and compare with timingSafeEqual. We recommend X-Signature-V2, and we send the -Previous headers for 24 hours after a rotation so you can deploy the new secret without dropping deliveries.

What statuses can a session return?

Ten exact strings: "Not Started", "In Progress", "Approved", "Declined", "In Review", "Awaiting User", "Resubmitted", "Expired", "Abandoned" and "Kyc Expired". They are case-sensitive and include spaces, so match on the string itself. Treat "In Review" as pending, not as a pass.

What does the integration cost for 1,000 verifications a month?

A full KYC check is $0.33 at list price, so 1,000 checks are $330.00 a month. Adding AML screening at $0.20 for 200 users adds $40.00, for $370.00 in total. The Free plan gives $10.00 of monthly credit to the first eligible organization created with a work email on a company domain, and sandbox sessions are free.

Can I test declines and manual review without real documents?

Yes. Sandbox checks are mocked, and sandbox sessions accept a sandbox_scenario slug from GET /v1/sandbox/scenarios/, which expands the scenario's magic values onto the session so it reproduces that outcome. You can arm or re-arm a scenario after create while the session is still "Not Started". The slug comes back in the webhook as sandbox_scenario.

Should my Next.js app send a Bearer token to the Didit verification API?

Use x-api-key with POST https://verification.didit.me/v3/session/. The response gives your app a hosted URL where the user captures their document and selfie. Bearer tokens belong to our account host, which handles account and application management, not to the verification routes.

Which checks can one Next.js integration run?

A hosted User Verification workflow runs the checks you publish in it, such as ID document verification, liveness, face match 1:1, AML screening and proof of address. The workflow determines which of those checks run, so you change them in the workflow rather than in your Next.js code. Standalone APIs run outside a session, with their own calls and their own prices.

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.