Why Next.js Users Get Signed Out on Multi-Instance Hosting
A Didit refresh token is spent once. On several server instances two processes can rotate the same token at the same moment, the second one loses, and the person has to sign in again.

Contents
In this guide
Jump to the part you need.
Didit Authentication with the Next.js SDK fits App Router teams that want hosted sign-in, HttpOnly session cookies and no token handling in the browser. The first 50,000 active users each month are free on every plan, then $0.02 per active user per month. The catch is the one this page answers: a refresh token is spent once per server process, so an app spread across several instances can end a session when two processes refresh at the same moment.
Last updated: November 26, 2026. Prices checked against the live Didit price feed on November 26, 2026.
Connect Didit to an AI assistant through the Didit MCP server, hosted at https://mcp.didit.me/mcp with OAuth sign-in.
| What the person sees | What is happening | Where to fix it |
|---|---|---|
| Signed out after a page navigation, at random, only in production with several instances | Two server processes rotated the same refresh token at the same moment and the second one presented a spent token | Let diditAuthProxy own rotation, and remove every other refresh path |
| Signed out on one device after a session was revoked or ended somewhere else | The session check fails at most DIDIT_SESSION_CACHE_SECONDS after revocation, 30 seconds by default | Lower it for the whole application if 30 seconds is too slow, or set 0 to check every time |
| Requests return 401 right after a custom domain went live | Access tokens issued under the old issuer fail GET /session/ until they are refreshed, within 5 minutes | Update DIDIT_AUTH_ISSUER, or accept both issuers for 5 minutes |
Sign-in fails with invalid_grant | The code was used twice or is past 60 seconds, or the redirect URL does not match | Compare the registered redirect URL character by character |
Start free in the sandbox at https://business.didit.me/, no sales call. Developers can connect an AI assistant to Didit through the MCP server at https://didit.me/developers/mcp/. The product behind this guide is Didit Authentication, and every number below comes from the pricing page.
One server process, and then several
On a single process the flow is boring, which is what you want. The person signs in on your hosted page, returns to your redirect URL with a one-time code, and your app exchanges that code for an access token, an ID token and a refresh token. The access token carries expires_in of 299 seconds in the token response, so it lasts at most 5 minutes. The refresh token rotates on every use.
The Next.js SDK keeps this out of the browser. The package @didit-protocol/auth-nextjs stores the session in HttpOnly cookies set by your server, and the proxy serves the /auth/* routes for you. When the access token has expired, the proxy rotates the refresh token first, so pages render with a valid session instead of bouncing the person to sign-in.
Now add instances. A refresh token is spent once per server process. If a person has two requests in flight and they land on two different instances while the access token is expired, both instances decide they need a rotation. The first one spends the refresh token and gets a new pair. The second one presents a token that is already spent. Didit treats that as refresh reuse, the session ends, and the person is looking at a sign-in page.
That is why the symptom looks random. It is not the person, the device or the browser. It is the timing of two refreshes inside one session, and it only shows up once you run more than one server process or more than one instance.
The settings that decide how fast a session dies
DIDIT_SESSION_CACHE_SECONDS
The package reads DIDIT_SESSION_CACHE_SECONDS, default 30. It is an application-wide setting, not a value you tune per route. It controls how quickly a revoked session stops working: auth() checks the session with Didit, and a session revoked from the console or from another device stops working within that window. Set it to 0 when the application needs a session check on every request.
Access token lifetime
An access token stays valid until it expires, within 5 minutes. Verifying the signature is not enough before a sensitive action, because a revoked session can still hold a token that has not expired. The docs are explicit: check the live session with GET /session/ before a payout, a bank account change or an email change.
Key rotation and the JWKS cache
Signing keys rotate every 30 days, and the JWKS answers with a 5-minute cache, so a cached copy keeps verifying across a rotation. Cache keys by kid, and fetch the JWKS again, at most once a minute, when a token names a key you do not have. A revoked key is removed at once, and GET /session/ rejects every token that key signed.
Authentication is new. Every call on this page uses end-user credentials or none at all. Never send your verification API key or a console token to these endpoints.
Prerequisites
| Item | What it must be | Where it is set |
|---|---|---|
| Didit plan | Any plan. Sandbox testing is free and unlimited, and the first 50,000 active users each month are free | Sign up at business.didit.me |
| Application | A Sandbox application. Authentication is on from the start | Application switcher in the Business Console |
| Client runtime | Next.js 15.5 or later, or 16, with React 19 and Node.js 20 or later | Your app |
| Package | @didit-protocol/auth-nextjs version 0.3.0 | npm |
| Publishable key | pk_test_... in the sandbox. It is public and names your sign-in origin | Authentication > Developers |
| Redirect URL | Registered exactly, for example http://localhost:3000/auth/callback | Authentication > Security and sessions > Redirect URLs and allowed origins |
| Sign-in method | At least one is on. A new application starts with every method off | Authentication > Sign-in methods |
Install and configure the SDK
1. Open your sandbox application. In the Business Console, use the application switcher to select your Sandbox application, then open Authentication. A Live application turns Authentication on from the Products page instead. Until it is on, every runtime route for that application returns 404.
2. Register your callback and origin. Open Authentication > Security and sessions > Redirect URLs and allowed origins and add the redirect URL and the allowed origin. Didit only returns a person to a redirect URL you registered, character by character. A Sandbox application accepts http:// on localhost; a Live application accepts https:// only.

3. Turn on a sign-in method. Open Authentication > Sign-in methods and turn on Email code. Add Passkeys too if you want them. The hosted page offers only the methods you turn on.

4. Copy the publishable key. Open Authentication > Developers and copy the Publishable key. In a Sandbox application it starts with pk_test_. The publishable key is public. Never put the Secret key in browser or mobile code.

5. Install the package.
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
# Optional. Default 30. 0 checks the session with Didit every time.
DIDIT_SESSION_CACHE_SECONDS=30
A value that is not a Didit key fails at startup with DiditAuthConfigError. The publishable key names your sign-in domain, so there is no other address to set.
6. Add the proxy, the layout and the sign-in page. Create proxy.ts on Next.js 16, or 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).*)"] };
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>
);
}
// app/sign-in/page.tsx
export { SignIn as default } from "@didit-protocol/auth-nextjs";
diditAuthProxy takes protect (paths that need a signed-in person), signInUrl (default /auth/sign-in) and afterSignOutUrl (default /). The proxy serves the /auth/* routes, so you add no route files. POST /auth/sign-out ends the session at Didit and clears the cookies.
7. Read the session on the server. Use auth.protect() in a page and auth() in a route handler.
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>;
}
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 });
}
The docs give one instruction that matters here: do not rely on the proxy alone. Call auth() at each data access and mutation, because a frontend session check only controls what you show. The proxy must run on the route, so an expired access token is refreshed first.
If your team works from an AI assistant
The Didit MCP server is hosted at https://mcp.didit.me/mcp with OAuth sign-in, and it is free on every plan. Developers can connect an AI assistant to Didit through the MCP server while they wire the Next.js app, and the setup is documented at didit.me/developers/mcp. The API recipe route is the Authentication API reference at docs.didit.me/authentication/api-reference.
What Didit stores and sends
You do not submit sign-in events yourself. Didit records them on the person with the same vendor_data, next to their verifications and transactions. Subscribe a webhook destination to the auth.* types you need, and use Try Webhook in the console to send a sample of each type.
| What happened in your app | Stored event | Webhook |
|---|---|---|
| Sign-up | auth.signup | auth.signup |
| Sign-in | auth.login | auth.login |
| Failed sign-in | auth.login_failed | auth.login_failed |
| Sign-out, or a session revoked | auth.logout | None |
| Password reset requested | auth.password_forgot | auth.password_reset_requested |
| Password reset completed | auth.password_reset | auth.password_reset_completed |
| Password changed | security.password_changed | None |
| Authenticator added or changed | security.mfa_changed | auth.mfa_changed |
| Sign-in from a new device | security.device_changed | auth.new_device |
| Account locked or blocked | security.account_locked | auth.account_locked |
| Field | What it tells you |
|---|---|
event.payload.method | The method used, for example password or passkey |
event.payload.reason | Why a sign-in failed or an account was locked |
event.device.persistent_device_id | The device ID, used to decide whether a device is new |
event.device.fingerprint | The fingerprint, the second half of the new-device check |
event.device.bot_score | The bot score when the client sent one |
event.ip.is_vpn_or_tor, event.ip.country | Network context for a session that ended unexpectedly |
| Session ID | Carried on the event and returned by the token exchange as session_id |
Reading these needs the list:transactions or read:authentication permission. Each event carries the IP address, the device context and the session ID, so a report of a surprise sign-out can be checked against what actually happened.
The multi-instance checklist
- Keep one spender per session. The proxy rotates the refresh token before rendering. Remove any custom route, cron or client loop that calls the token endpoint with a
refresh_tokengrant, because that is a second spender on the same token. - Run the proxy on every route that renders protected content, and call
auth()at each data access and mutation. - Read the access token with
getToken()where you need it. It returns the person's short-lived token, so your own code never exchanges a refresh token next to the proxy. - Keep
DIDIT_SESSION_CACHE_SECONDSat its documented default of30, and set0when the application needs a session check on every request. It is an application-wide setting, not a per-route one. - Verify the access token on your backend against the JWKS, checking
iss,aud,expandtyp: at+jwt. Cache keys bykid. - When a custom domain goes live, update
DIDIT_AUTH_ISSUERin the same deploy, or accept both issuers for 5 minutes.
Test in the sandbox
Every Sandbox application has Authentication on, accepts http://localhost callbacks and Didit test credentials for social sign-in, and is never billed. Use it for all of the following before you touch a Live application.
Expected success. Open /auth/sign-in, pick Email code, enter an address, type the six-digit code, and land back on the page you asked for. The person appears under Authentication > Sign-ins, and auth.protect() returns a session with session.user.email and session.user.vendorData. GET /auth/session returns the session, and GET /auth/token returns a token you can verify with verifyToken.
| Error or symptom | Cause | Fix |
|---|---|---|
DiditAuthConfigError at startup | DIDIT_PUBLISHABLE_KEY is not a Didit key | Copy it again from Authentication > Developers |
400 invalid_grant | Code unknown, used or past 60 seconds, verifier or redirect URL mismatch, the person is blocked, or the method they used is off | Exchange within 60 seconds, register the exact redirect URL, turn the method back on |
400 invalid_client | client_id is not your application ID | Use the application ID of the same application |
400 mfa_required | The sign-in did not meet your MFA policy | Handle the challenge, or relax the policy for the sandbox |
| Every runtime route returns 404 | Authentication is not on for the application | Turn it on from the Products page for a Live application |
401 from GET /session/ after a domain change | The token was issued under the previous issuer | Update DIDIT_AUTH_ISSUER, or wait for the refresh, within 5 minutes |
| Signed out after a redeploy with more instances | Two processes refreshed one token at the same moment | Remove the extra refresh path and let the proxy rotate |
Turning it off
To stop a session, call POST /auth/sign-out, which ends the session at Didit and clears the cookies. A sign-out is stored as auth.logout and sends no webhook. To stop using Authentication for an application, turn the product off. In a Sandbox application you can turn products on and off freely. Remove the redirect URLs from Security and sessions when the address is no longer yours, and uninstall @didit-protocol/auth-nextjs if you are going back to your own sign-in.
What it costs on both ends
On the Didit side, sign-in is priced by active users, not by sign-in. The first 50,000 active users each month are free on every plan. After that the price book lists Active users after the free allowance at $0.02 per active user per month. The plans around it are Free at $0.00 with $10.00 of monthly credit, Growth at $99.00 a month with $115.00 of credit and 4% off every Didit price, Scale at $299.00 a month with $350.00 of credit and 10% off, and Enterprise from $15,000 a year on an annual contract. The price book has no line for a session check, so setting DIDIT_SESSION_CACHE_SECONDS to 0 changes request volume, not a Didit charge. The discovery and JWKS documents allow 1,200 requests a minute and 12,000 an hour per IP address.
On your side, the boundary is short. The SDK stores the session in HttpOnly cookies set by your server, and the page never sees the tokens.
Worked example, 80,000 monthly active users. 80,000 minus 50,000 free users leaves 30,000 billable active users at $0.02 each, which is $600.00 a month. On Free the $10.00 monthly credit comes off that, so the bill is $590.00. On Growth the unit price is $0.0192, so 30,000 multiplied by $0.0192 is $576.00; the $115.00 monthly credit brings it to $461.00, and the $99.00 plan fee makes $560.00. On Scale the unit price is $0.018, so 30,000 multiplied by $0.018 is $540.00; the $350.00 monthly credit brings it to $190.00, and the $299.00 fee makes $489.00. With credits and fees counted, Scale is the cheapest of the three at this volume. If 25,000 of those people also complete a full ID check at $0.33, that adds 25,000 multiplied by $0.33, which is $8,250.00, billed separately from sign-in.
Sources
- Didit docs: Next.js quickstart
- Didit docs: Tokens and JWKS
- Didit docs: Authentication integration guide
- Didit docs: Authentication quickstart
- Didit docs: Authentication overview
- Didit docs: Authentication events and webhooks
- Didit pricing and pricing in the docs
- Didit MCP server
- Didit full product facts
Next step: create a Sandbox application at https://business.didit.me/, install @didit-protocol/auth-nextjs, and watch one session survive a redeploy across two instances. No sales call, and the sandbox is free.
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
Why do Next.js users get randomly signed out when the app runs on several server instances?
A Didit refresh token is spent once per server process. When two instances see an expired access token for the same person at the same moment, both try to spend the same refresh token; the second one presents a spent token, refresh reuse detection ends the session, and the person signs in again. The fix is to keep a single spender, which in the Next.js SDK is the proxy that rotates the token before rendering.
Does the Next.js SDK rotate the refresh token for me?
Yes. With @didit-protocol/auth-nextjs, the proxy serves the /auth/* routes and, when the access token has expired, it rotates the refresh token first so pages render with a valid session. The session lives in HttpOnly cookies set by your server, so the page never sees the tokens.
What does DIDIT_SESSION_CACHE_SECONDS do?
It is an application-wide setting that controls how fast a revoked session stops working. The default is 30, which means a session revoked from the console or from another device stops working within 30 seconds. Setting it to 0 checks the session with Didit on every request, which adds requests but removes the window.
How long does a Didit access token last?
At most 5 minutes. The token response returns expires_in of 299 seconds, and an access token stays valid until it expires even if the session behind it was revoked. Check the live session with GET /session/ before a sensitive action.
Do I need sticky sessions for Didit Authentication on Next.js?
The docs do not ask for sticky sessions. What they require is that the proxy runs on the route so an expired access token is refreshed first, and that you call auth() at each data access and mutation instead of trusting the proxy alone.
Why did every request start returning 401 after I activated a custom domain?
When a custom domain becomes active, it replaces the default host as the issuer. Access tokens issued under the default host fail GET /session/ until they are refreshed, within 5 minutes. Update DIDIT_AUTH_ISSUER when you activate the domain, or accept both issuers until the older tokens expire.
Is there a webhook when a session ends or a person is signed out?
No. A sign-out or a revoked session is stored as auth.logout and sends no webhook. Webhooks exist for auth.signup, auth.login, auth.login_failed, auth.new_device, auth.account_locked, auth.mfa_changed and the password reset pair.
How do I sign a person out in code?
Send POST /auth/sign-out. The proxy ends the session at Didit and clears the cookies, then takes the person to afterSignOutUrl, which defaults to /.
Can I use refresh tokens outside the SDK?
You can, because the token endpoint takes the refresh_token grant. Do not run it next to the proxy for the same session, because that creates a second spender on a token that works once. If you support a backend of your own, send the short-lived access token and verify it with verifyToken from @didit-protocol/auth/server.
Does the package work with the Next.js Pages Router?
The quickstart documents the App Router, Next.js 15.5 or later (or 16) and React 19, at package version 0.3.0. If you are not on the App Router, the docs list @didit-protocol/auth for single-page web apps, with a backend that verifies the access token.
How much does Didit Authentication cost for a Next.js app?
The first 50,000 active users each month are free on every plan, then $0.02 per active user per month at list price. Growth is $99 a month with 4% off every Didit price and $115 of monthly credit, and Scale is $299 a month with 10% off and $350 of credit. 30,000 billable active users cost $590.00 on Free after the $10 credit, $560.00 on Growth and $489.00 on Scale.
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

