How to Add Didit Authentication to a Next.js App with HttpOnly Cookies
Install @didit-protocol/auth-nextjs and read the session with auth() on the server. Your server sets HttpOnly cookies browser JavaScript cannot read; client code requests the short-lived access token explicitly.

Contents
In this guide
Jump to the part you need.
Use @didit-protocol/auth-nextjs for hosted Didit sign-in on the Next.js App Router with React 19. Your Next.js server sets HttpOnly session cookies, and auth() reads the session on the server. The first 50,000 active users each month are free. Additional active users cost $0.02 each at list price. Call auth() at every data access and mutation, even on routes protected by the proxy.
Last updated: November 26, 2026. Prices checked against the live Didit price feed on November 26, 2026.
| Item | What you get |
|---|---|
| Package | @didit-protocol/auth-nextjs, version 0.3.0 on npm |
| Runtime | Next.js 15.5 or later, or Next.js 16, with React 19. Node.js 20 or later for the local test setup described in the Authentication quickstart |
| Where session tokens live | HttpOnly cookies set by your server. Browser JavaScript cannot read those cookies directly. Client code can ask for the short-lived access token with useAuth().getToken() or GET /auth/token |
| What the server reads | auth() returns session, userId, sessionId, getToken, getStepUp |
| Backend check | ES256 signature against the issuer JWKS, then iss, aud, exp and typ: at+jwt, then GET {issuer}/session/ before a sensitive action, and a step-up when a rule applies |
| Sign-in surface | Hosted pages at https://<name>.auth.didit.me (sandbox: https://<name>.sandbox.auth.didit.me) |
| Price | We include the first 50,000 active users each month at no charge and bill $0.02 USD list price per additional active user month |
| Optional verification | USD list prices: liveness $0.10, selfie login $0.10, full ID $0.33 per completed check |
| Testing | Free sandbox application, accepts http://localhost, never billed |
Start free in the sandbox at business.didit.me, no sales call. For developers who want an assistant to write the wiring, connect Didit to an AI assistant through the Didit MCP server. Every module price is on didit.me/pricing.
How the pieces fit together
Didit Authentication separates four parts. The @didit-protocol/auth-nextjs package starts sign-in, and your Next.js server sets the session cookies during the callback. Your sign-in origin, which is your application's Didit address, runs the hosted pages, the token endpoint and the signing keys. Your backend verifies the token and decides what the person may do. The Didit console is the configuration surface for your application, its people and their sessions, and Didit sends auth.signup, auth.login and auth.new_device events to the webhook endpoints your server subscribes to. Read the full model in the Authentication integration guide.
Because the package runs on the server, no Didit API key and no client secret belongs in the app. The publishable key is public, and the code exchange is protected by PKCE instead of a client secret. That is the main reason to choose @didit-protocol/auth-nextjs over the browser SDKs for an App Router project: your Next.js server sets the session tokens in HttpOnly cookies during the callback, so browser JavaScript cannot read those cookies directly. That is not the same as hiding every token. Client code that needs to call another backend asks for the short-lived access token explicitly, through useAuth().getToken() or GET /auth/token, and the browser sends the cookies with requests that match their scope.
Prerequisites
| Requirement | Detail | Where |
|---|---|---|
| Didit account | Free, with a Sandbox application. Every Sandbox application has Authentication turned on | Business Console |
| Plan | The Free plan includes $10 in monthly credit for the first organization created with an eligible company work email. The credit excludes phone verification codes. Sandbox testing is free on every plan | Pricing |
| Application type | Sandbox while you build. A Live application turns Authentication on from the Products page | Prepare your application |
| Publishable key | pk_test_... or pk_live_.... It names your sign-in origin, so there is no other address to set | Authentication > Developers |
| Redirect URL | http://localhost:3000/auth/callback, registered character for character | Authentication > Security and sessions > Redirect URLs and allowed origins |
| Allowed origin | http://localhost:3000, needed when you build your own sign-in screens in the browser | Same page |
| Sign-in method | Email code, passkeys, social, or any method you enable. A new application starts with every method off | Authentication > Sign-in methods |
| Local test setup | Node.js 20 or later, the prerequisite the general Authentication quickstart lists, and a Next.js app on http://localhost:3000. The package itself documents Next.js 15.5 or later with React 19 | Your machine |
Sandbox accepts http:// on localhost, and Live accepts https:// only. Plan for that difference before you deploy.
Step by step: hosted sign-in with HttpOnly cookies on the App Router
Step 1: open the application and register the callback
In the Business Console, use the application switcher to select your Sandbox application, then open Authentication. Go to Security and sessions, then Redirect URLs and allowed origins, and add two entries: the redirect URL http://localhost:3000/auth/callback and the allowed origin http://localhost:3000. Didit returns a person only to a redirect URL you registered, character for character. The redirect URL must match exactly, and the allowed origin is what you need when you build your own browser sign-in screens, as the Next.js quickstart shows.
Step 2: turn on the sign-in methods you want
Open Authentication, then Sign-in methods, and turn on Email code. Add Passkeys if you want passkey sign-in, or Google with Didit test credentials, which work in Sandbox without an app of your own. The hosted page offers only the methods you turn on. Every method is described in sign-in methods.

Step 3: copy the publishable key and install the package
Open Authentication, then Developers, and copy the publishable key. In a Sandbox application it starts with pk_test_. Install the package and create two environment variables.
npm install @didit-protocol/auth-nextjs
# .env.local: Authentication > Developers in the Didit console.
DIDIT_PUBLISHABLE_KEY=pk_test_...
# Register this exact address as a redirect URL of the application.
DIDIT_REDIRECT_URI=http://localhost:3000/auth/callback
A value that is not a Didit key fails at startup with DiditAuthConfigError. The package also reads DIDIT_SESSION_CACHE_SECONDS, which defaults to 30. Set DIDIT_SESSION_CACHE_SECONDS to 0 to check with Didit every time the app reads the session with auth().
Step 4: add the proxy and wrap the app in DiditAuth
The proxy file is proxy.ts on Next.js 16 and middleware.ts on Next.js 15. It serves the /auth/* routes for you, so you add no route files.
// proxy.ts on Next.js 16, middleware.ts on Next.js 15
import { diditAuthProxy } from "@didit-protocol/auth-nextjs/server";
export default diditAuthProxy({ protect: ["/account"] });
export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"] };
// app/layout.tsx
import type { ReactNode } from "react";
import { DiditAuth } from "@didit-protocol/auth-nextjs";
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
<DiditAuth>{children}</DiditAuth>
</body>
</html>
);
}
The proxy options are protect (paths that need a signed-in person), signInUrl (default /auth/sign-in) and afterSignOutUrl (default /).
Step 5: add the hosted sign-in and sign-up pages
Two one-line files open the hosted method chooser, where Create account starts registration. Both send someone already signed in straight on to redirect_url.
// app/sign-in/page.tsx
export { SignIn as default } from "@didit-protocol/auth-nextjs";
// app/sign-up/page.tsx
export { SignUp as default } from "@didit-protocol/auth-nextjs";
For a sign-in button, link to the documented route rather than writing a client handler. The proxy serves GET /auth/sign-in, which opens the hosted page with PKCE and sends the person back to the path you pass in redirect_url.
<a href="/auth/sign-in?redirect_url=/account">Sign in</a>
| Route | Purpose |
|---|---|
GET /auth/sign-in, /auth/sign-up, /auth/reauthenticate | Open the hosted page with PKCE. redirect_url is where the person returns. |
GET the path of DIDIT_REDIRECT_URI | Callback: checks the state, exchanges the code and stores the session. |
POST /auth/sign-out | Ends the session at Didit and clears the cookies. |
GET /auth/session, GET /auth/token | The session and the access token, for your own pages. |
POST /auth/step-up, GET /auth/step-up/{id} | Asks the step-up rules about an action, and reads a step-up's outcome. |
The proxy also serves POST /auth/exchange for sign-ins started on your own screens, and GET /auth/agents and DELETE /auth/agents/{id} for the person's agent grants. The Next.js quickstart lists every route. Keep the two session routes apart: GET /auth/session is your app's own route that reads the local session, while GET {issuer}/session/ is the Didit endpoint your backend calls before a sensitive action.
Step 6: read the session on the server with auth()
// app/account/page.tsx
import { auth } from "@didit-protocol/auth-nextjs/server";
export default async function Account() {
const session = await auth.protect(); // sends a signed-out visitor to sign in
return <p>{session.user.email} {session.user.vendorData}</p>;
}
// app/api/me/route.ts
import { auth } from "@didit-protocol/auth-nextjs/server";
export async function GET() {
const { session, userId } = await auth();
if (!session) return Response.json({ error: "unauthorized" }, { status: 401 });
return Response.json({ userId, vendorData: session.user.vendorData });
}
auth.protect() returns the session, or sends a signed-out visitor to sign in and back to the page they asked for. Do not rely on the proxy alone: call auth() at each data access and mutation. Because auth() checks the session with Didit, a session revoked from the console or from another device stops working within DIDIT_SESSION_CACHE_SECONDS. When the access token has expired, the proxy rotates the refresh token first, so pages render with a valid session.
Client components use SignedIn, SignedOut, UserButton, ConnectedAgents, useAuth() and useUser(), which the package re-exports from @didit-protocol/auth-react. Under <DiditAuth> they render signed in or out from the first server render. Use them for presentation only, and keep every decision on the server.
Step 7: verify the token and check the live session before sensitive actions
A frontend session check only controls what you show. Your backend makes every decision from a verified token. Send the access token from getToken() in the Authorization header and verify it on the server. The base verifyToken call from the quickstart comes first, and the checks from the integration guide wrap it.
Every protected bearer-token request must pass the checks the integration guide lists: verify the ES256 signature against the issuer's JWKS, check iss, check aud against your application ID, check exp, check typ: at+jwt, and apply the route's actor policy. On a human-only route, require act to be null. Reject the request before you read sub or vendor_data if the signature, issuer, audience, expiry, token type or the route's actor policy fails. Apply these requirements whatever verifier you use, an SDK or any JWT library.
// server.ts
import { verifyToken } from "@didit-protocol/auth/server";
// Start with signature, issuer and expiry verification.
const claims = await verifyToken(token, { publishableKey: process.env.DIDIT_PUBLISHABLE_KEY });
Before using sub or vendor_data, also require the expected aud, the at+jwt token type and an act value allowed by the route. Reject the request if any check fails.
verifyToken checks the ES256 signature against your issuer's published keys, the issuer and the expiry. That is the starting point, not the whole contract.
Before a risky action, run the sequence in this order.
- Verify the bearer token, then call
GET {issuer}/session/with it before the sensitive action. - Ask Didit whether a step-up rule applies to that action, with the initiation call
POST {issuer}/step-up/. If the answer isrequired: false, proceed only when the other authorization checks pass. - If a step-up is required, send the person to the returned
verification_url. On the backend, readGET {issuer}/step-up/{step_up_id}/with an access token from the same session, and proceed only when the status isapproved. A query string on the return URL proves nothing.
The tokens and JWKS page lists every claim rule, including key rotation every 30 days.

Field and event mapping
| What you read | Source | Use it for |
|---|---|---|
session.user.email | The session's email field | Showing the signed-in account in the interface |
session.user.vendorData | The vendor data returned in the session | Reading the vendor data your app attached, when the session carries it |
userId | The person id, backed by the token's sub claim | The identifier for linking the Didit person to your own records |
sessionId | session_id from the token exchange | Auditing and revoking a single session |
getToken() | Short-lived access token, 5 minutes | Authorization: Bearer to another backend |
POST {issuer}/step-up/ | Asks the step-up rules whether one applies to an action | Starting the step-up when Didit returns a required rule |
GET {issuer}/step-up/{step_up_id}/ | The step-up's outcome, read by your backend | Allowing a payout, bank or contact change only on an approved result, which is required when Didit returns a required step-up |
auth.signup, auth.login, auth.new_device | Webhooks sent by your sign-in origin | Welcome emails, new device alerts, your own audit log |
verification_required | Sign-in response when your policy asks for a check | Sending the person to verification_url on your own screens |
If you also run verifications, the same person carries the sign-in, the verification sessions and the transactions, because each check runs as a verification session of your own application with the person's vendor_data. See verified identity for the sign-up levels and the step-up rules.
Test with sandbox data: expected result, errors and fixes
- Run the app on
http://localhost:3000and open/auth/sign-in. - Choose Email code and enter a test email address you can access, so you can retrieve the six-digit code. The hosted page sends a code that lasts 10 minutes.
- Type the code. Didit returns the browser to
/auth/callbackwithcodeandstate. - Open
/account. The page renders the session's email, and the cookies are HttpOnly in the browser's application panel. - Call
/api/mewhile signed in. The route returnsuserIdandvendorData. - Sign out with
POST /auth/sign-out, then call/api/meagain. It returns401, because the session is gone. - Open Authentication, then Sign-ins in the console. The sign-in is listed there with its session.
A first sign-in with an address that has no account creates one, because the default sign-up policy lets anyone sign up. Nothing in a Sandbox application is billed.
| Symptom | Cause | Fix |
|---|---|---|
DiditAuthConfigError at startup | The publishable key is not a Didit key | Copy the key again from Authentication, then Developers |
| The hosted page rejects the redirect before sign-in starts | The redirect URL is not registered character for character | Register the exact URL, then start again from /auth/sign-in |
invalid_grant on the callback | The callback code exchange failed: the redirect URI differs from the registered one, the PKCE verifier is wrong, or the code expired or was already used | Keep the verifier from the same browser, exchange the code within 60 seconds, and register the exact URI |
401 unauthorized from your route handler | No session, or the proxy does not run on that route | Check the matcher and call auth() at the data access |
| A signed-in person suddenly loses access | The session was revoked in the console or ended on another device | Expected, within DIDIT_SESSION_CACHE_SECONDS |
| Localhost works, the deployed app fails | A Live application accepts https:// only | Register the https redirect URL and update the environment variables |
| No passkey button on the hosted page | The passkey method is off | Turn on Passkeys under Authentication, then Sign-in methods |
| New tokens fail offline verification after a key change | A JWKS cached up to 5 minutes earlier still holds the old key | Cache by kid and refetch at most once a minute when a key is unknown |
Disconnect a Next.js app from Didit Authentication
Sign people out with POST /auth/sign-out. The route clears the cookies and ends the session at Didit. UserButton takes an afterSignOutUrl, and the proxy's default is /, so each user returns to a known page. To remove the integration, first remove Didit's proxy wiring in proxy.ts or middleware.ts and every reference to the <DiditAuth> wrapper, the sign-in and sign-up pages and the auth() helpers, then uninstall @didit-protocol/auth-nextjs. In the console, delete the redirect URL and the allowed origin you registered for this app only if no remaining flow uses them.
Didit Authentication pricing and worked example
On the Didit side, Authentication is billed per billable active user-month. We include the first 50,000 active users each month at no charge and bill $0.02 USD list price per additional active user for that month. Optional identity verification is billed separately, per completed check at USD list price: liveness $0.10, selfie login $0.10, full ID $0.33. The @didit-protocol/auth-nextjs package, the MCP server, the SDKs and the workflow orchestrator are free.
Worked example: 80,000 active users in one month
- Active users: 80,000. The first 50,000 are free, so 80,000 minus 50,000 leaves 30,000 billable. 30,000 x $0.02 USD list price = $600.00.
- Liveness at sign-up for 12,000 new people: 12,000 x $0.10 USD list price = $1,200.00.
- Payout step-ups: 300 completed payout step-ups use selfie login for people with a face already on file. A selfie-login rule falls back to the $0.33 full ID check when Didit has no face for the person. 300 x $0.10 USD list price = $30.00.
- Total at USD list price: $600.00 + $1,200.00 + $30.00 = $1,830.00 for the month.
Usage draws from the month's plan credit first, then from top-ups. On the Scale plan the 10% discount applies to Didit prices: $1,830.00 x 0.90 = $1,647.00 of usage. Subtract the $350 of plan credit that Scale includes: $1,647.00 minus $350.00 = $1,297.00, the additional prepaid credit needed under the example's assumptions. Add the $299 monthly subscription fee, which is separate from usage: $1,297.00 + $299.00 = $1,596.00 for the month, assuming no starting top-up balance and all of the plan credit available. Unused monthly plan credit does not roll over.
Sources
- Next.js quickstart: package version, runtime requirements, environment variables, proxy, layout, routes,
auth(). - Authentication integration guide: architecture, hosted pages versus own screens, backend checks.
- Tokens and JWKS: ES256 claims, discovery, key rotation,
GET /session/,invalid_grantcases. - Authentication quickstart: sandbox setup, Node.js 20 prerequisite, callback registration,
verifyToken. - Sign-in methods: email code, magic link, passkeys, social, SSO, MFA.
- Verified identity: sign-up levels, step-up rules, per-check prices.
- Didit Authentication overview: the canonical Authentication product page, and turning Authentication on for a Live application.
- Pricing in the docs, didit.me/pricing and pricing as JSON: supporting billing rules and list prices. The SDK and token documentation listed above supports the technical numbers.
- Branding and custom domain: what changes when your own domain becomes the issuer.
- Agent access: what the
actclaim means for routes that accept AI agents. - Didit MCP server and switch to Didit.
Start in the sandbox at business.didit.me: it is free, it accepts http://localhost, and no sales call is needed. Add a sign-in method, install the package and read your first HttpOnly session today. Didit is infrastructure for identity and fraud, used by 4,000+ companies.
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 much does Didit Authentication cost in a Next.js app?
The first 50,000 active users each month are free on every plan, and after that we bill $0.02 USD list price per billable active user-month from prepaid credit. Any identity verification you add on top is billed per completed check at its own USD list price: $0.10 for liveness, $0.10 for selfie login, $0.33 for a full ID check. The package, the SDKs, the MCP server and the workflow orchestrator are free.
Where does @didit-protocol/auth-nextjs keep the access and refresh tokens?
Your Next.js server sets the session tokens in HttpOnly cookies during the callback exchange, so browser JavaScript cannot read those cookies directly. The browser sends the cookies with requests that match their scope, and server components, route handlers and server actions read the session with auth() from @didit-protocol/auth-nextjs/server. When client code needs a token for another backend, it asks for the short-lived access token explicitly with useAuth().getToken() or GET /auth/token.
Do I need a client secret or a Didit API key inside the Next.js app?
No. The hosted Next.js flow uses the publishable key and the registered redirect URI, and the sign-in flow requires neither a Didit API key nor a client secret. The publishable key is public and names your application's Didit sign-in origin, and the code exchange is protected by PKCE. A value that is not a Didit key fails at startup with DiditAuthConfigError.
How do I read the signed-in person in a server component?
Import auth from @didit-protocol/auth-nextjs/server and await auth.protect(). It returns the session, or sends a signed-out visitor to sign in and back to the page they asked for. The session carries user.email and user.vendorData, and auth() also returns userId, backed by the token's sub claim, and sessionId.
Why do I still need auth() on a route protected by the proxy?
Call auth() at every data access and mutation because a request can reach a route handler or server action directly. Reject the request if there is no session, then check that the signed-in user is allowed to read or change the requested data. The SDK can cache the session check for DIDIT_SESSION_CACHE_SECONDS, which defaults to 30 seconds.
How do I verify a Didit access token on a separate backend with JWKS?
Call verifyToken from @didit-protocol/auth/server with your publishable key, or verify the ES256 signature yourself against {issuer}/.well-known/jwks.json. Either way, every protected bearer-token request must check iss, check aud against your application ID, check exp and check typ: at+jwt, and on a human-only route reject any token whose act is not null. Keys rotate every 30 days, so cache by kid and refetch at most once a minute when an unknown key appears.
What is the difference between GET /auth/session and GET {issuer}/session/?
GET /auth/session is the route the proxy serves for your application's session endpoint, and it is what your own pages read for rendering. GET {issuer}/session/ is the Didit issuer endpoint, and your backend calls it with the person's access token before a sensitive action. GET /auth/session provides session data for rendering. Before a sensitive action, verify the bearer token, call GET {issuer}/session/ with that token, and enforce your app's authorization rules.
When should I check GET {issuer}/session/ after verifying the access token?
Before a sensitive action such as a payout, a bank account change or an email or phone change. An access token stays valid until it expires, within 5 minutes, but GET {issuer}/session/ fails at once when the session was revoked, went idle, expired, the person was blocked, or the session no longer meets your MFA policy.
How do I ask for a step-up before a payout?
Verify the bearer token and call GET {issuer}/session/ first, then ask Didit whether a step-up rule applies with POST {issuer}/step-up/, the initiation call. If the answer is required: false, proceed only when the other authorization checks pass. If Didit returns a required step-up, send the person to verification_url, then read GET {issuer}/step-up/{step_up_id}/ on your backend with an access token from the same session. An approved result is required, and a query string on the return URL proves nothing.
Does the Next.js package support passkey sign-in?
Yes. Passkeys are a sign-in method under Authentication, then Sign-in methods, and the hosted page on your application's Didit origin handles them. Passkeys belong to that origin, so on your own screens on another domain you send people to the hosted page for passkeys.
How do I sign someone out of a Next.js app?
Post to /auth/sign-out, which the proxy serves. It ends the session at Didit and clears the cookies. UserButton takes an afterSignOutUrl, and the proxy's afterSignOutUrl default is /.
What happens when the access token expires mid-session?
The proxy rotates the refresh token first, so the page renders with a valid session. Access tokens last at most 5 minutes, and getToken() returns a fresh one for calls to another backend. auth() rechecks the session with Didit, so a revocation shows up within DIDIT_SESSION_CACHE_SECONDS, 30 seconds by default.
Which versions of Next.js and Node.js does the package need?
The package documents Next.js 15.5 or later, or Next.js 16, with React 19, and version 0.3.0 is published on npm as @didit-protocol/auth-nextjs. The proxy file is proxy.ts on Next.js 16 and middleware.ts on Next.js 15. Node.js 20 or later is the prerequisite the general Authentication quickstart lists for its local test setup, not a statement of the package's own minimum.

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


