Supabase SSR on Next.js: Stale Sessions and Lock Timeouts
The session flips between signed-in and signed-out because the refreshed token is written to a cookie store that no longer exists. Adapter, proxy and lock fixes.

Introduction & Quick Summary
Symptom. A Next.js App Router app on @supabase/ssr behaves differently on every request. The user signs in, the dashboard renders their data, then one refresh later supabase.auth.getUser() returns null and the page redirects to /login. The terminal repeats Error: Cookies can only be modified in a Server Action or Route Handler, or the console shows NavigatorLockAcquireTimeoutError: Acquiring an exclusive Navigator LockManager lock "lock:sb-<ref>-auth-token" immediately failed while the session stops refreshing.
Cause. Three mechanisms fail together. createServerClient needs a getAll/setAll adapter, and since Next.js 15 cookies() is async, so a synchronous adapter reads an empty store. A Server Component is a render, not a mutation, so cookieStore.set() throws there and a try/catch keeps the render alive while discarding the refreshed token. And the proxy refreshes the token onto the response while the route handler downstream reads the request cookies, so the two halves of one request disagree.
Fix. Return the full cookie set from getAll, write it back only where writing is legal, and in the proxy copy every setAll cookie onto both the request and the response. Never build a second client inside one request: auth serialises refreshes through a lock, and two clients racing it is what times out.
Core Mechanics, Signatures & Reproducible Setup
@supabase/ssr splits one logical client into a server shape with a cookie adapter and a browser shape that reads document.cookie. If the adapter is wrong the two disagree and the session appears to flip between signed-in and signed-out.
// lib/supabase/server.ts — Next.js 15+/16, @supabase/ssr 0.5+
import { createServerClient } from "@supabase/ssr";
import { cookies } from "next/headers";
export async function createClient() {
const cookieStore = await cookies(); // async since Next.js 15
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll: () => cookieStore.getAll(), // must return every chunk
setAll(cookiesToSet) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options),
);
} catch {
// Server Component render: writes are illegal here.
// The proxy is responsible for persisting the refresh.
}
},
},
},
);
}To reproduce: guard a page with getUser(), set the access token lifetime to 60 seconds, wait past expiry, reload twice. The first request returns the user because getUser() refreshes in memory; the second returns null because the new token went to a cookie store that no longer exists. The proxy is what makes the refresh persist. In Next.js 16 the convention is proxy.ts with an exported proxy function; middleware.ts still loads but is deprecated, and runtime cannot be configured because proxy always runs on Node.js.
// proxy.ts
import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";
export async function proxy(request: NextRequest) {
let response = NextResponse.next({ request });
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll: () => request.cookies.getAll(),
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) =>
request.cookies.set(name, value), // downstream reads
);
response = NextResponse.next({ request });
cookiesToSet.forEach(({ name, value, options }) =>
response.cookies.set(name, value, options), // browser receives
);
},
},
},
);
const { data: { user } } = await supabase.auth.getUser(); // forces refresh
if (!user && request.nextUrl.pathname.startsWith("/dashboard")) {
const url = request.nextUrl.clone();
url.pathname = "/login";
return NextResponse.redirect(url);
}
return response;
}request.cookies.set() must run before NextResponse.next({ request }) is rebuilt, or the forwarded request keeps the old header, and the return value must be the reassigned response.
Key Comparison Table
| Concern | Next.js 14 | Next.js 15 | Next.js 16 |
|---|---|---|---|
cookies() | synchronous | Promise, must await | same as 15 |
| Interception file | middleware.ts, edge | middleware.ts, edge or node | proxy.ts, node only |
| Exported function | middleware | middleware | proxy |
| Cookie write in a render | throws | throws | throws |
| Cookie adapter | Works in a render | Persists the refresh | Typical failure |
|---|---|---|---|
getAll / setAll | yes, writes skipped | yes, via proxy | none when the proxy returns its response |
get / set / remove | partly | unreliable | drops …-auth-token.1 chunks |
| Omitted entirely | reads document | never | null user every request |
| Two clients per request | yes | no | NavigatorLockAcquireTimeoutError |
Cookies beyond roughly 4 KB are chunked into sb-<ref>-auth-token.0, .1; an adapter returning only the base name returns half a session.
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Cookies can only be modified in a Server Action or Route Handler
The message is literal: set() is legal in a Server Action, a Route Handler, and proxy, never during a render. Catching it is correct only if something else performs the write. If the loop persists, check the matcher — ["/dashboard/:path*"] never runs for /, so a refresh there is thrown away.
const { data: { user } } = await (await createClient()).auth.getUser();
if (!user) redirect("/login"); // redirect, never a manual cookie delete2. Reading the signed-out loop instead of guessing
The loop has three breakages and one log line separates them:
const { data: { session } } = await supabase.auth.getSession();
console.log({
hasCookie: (await cookies()).getAll().some(c => c.name.startsWith("sb-")),
sessionExpiry: session?.expires_at,
now: Math.floor(Date.now() / 1000),
});hasCookie: false means the adapter never got the chunks; a past expiry with hasCookie: true means the refresh never persisted; a null session with both healthy means a client created before the proxy ran.
3. NavigatorLockAcquireTimeoutError and the 2.107 change
@supabase/auth-js serialises refresh through the Web Locks API so two tabs cannot refresh the same token and invalidate it for each other. The auto-refresh tick asks for its lock with a 0 ms timeout, so it fails immediately when another holder is active. Before supabase-js 2.107.0 the mutex could also deadlock: awaiting another Supabase call inside onAuthStateChange waited on the lock the callback already held, and the next query never resolved.
// 1. 2.107.0 removed the navigator.locks mutex
npm install @supabase/supabase-js@^2.107.0
// 2. older versions: keep the callback synchronous
supabase.auth.onAuthStateChange((_event, session) => {
setSession(session);
setTimeout(() => void hydrateProfile(), 0); // defer Supabase calls
});A custom lock function disables the browser lock if you cannot upgrade, trading a warning for a rarer bug — two tabs racing one refresh — so treat it as temporary.
4. A Server Action must revalidate what it rendered
A Server Action runs after the proxy, so its cookies are fresh, but the tree it returns was rendered with the pre-action state.
"use server";
import { revalidatePath } from "next/cache";
export async function signOut() {
const supabase = await createClient();
await supabase.auth.signOut();
revalidatePath("/", "layout"); // clears the cached tree that read the user
redirect("/login");
}Without it, sign-out works and the header keeps the avatar until a hard reload.
5. Route Handlers can write, so let them
// app/auth/callback/route.ts
export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url);
const code = searchParams.get("code");
const supabase = await createClient();
if (code) {
const { error } = await supabase.auth.exchangeCodeForSession(code);
if (!error) return NextResponse.redirect(`${origin}/dashboard`);
}
return NextResponse.redirect(`${origin}/login?error=callback`);
}The write lands in the response because a handler's cookie store is mutable. The same call in a Server Component returns a session already gone on the next request.
6. getSession() versus getUser() on the server
getSession() decodes the JWT without verifying it: fine for display, wrong for authorisation. getUser() calls the auth server, verifies and refreshes; use it in proxy and every guard.
const { data: { user }, error } = await supabase.auth.getUser();
if (error || !user) redirect("/login");
// authorise against user.id, never session.user from getSession()Common Compilation/Runtime Mistakes & Version Gotchas
cookies()withoutawait. It returns a Promise in Next.js 15 and 16; the adapter then calls.getAll()on a Promise, and the failure surfaces far away asCannot read properties of undefined.- One client per render.
createBrowserClientin a component body subscribes anew every render. Use a module-level singleton oruseState. middleware.tsleft on Next.js 16. It runs, butruntimein its config now fails the build;npx @next/codemod@canary middleware-to-proxy .renames file and export.- Redirect inside
try/catch.redirect()throws a control-flow exception, and catching it swallows the navigation. @supabase/ssr0.4 and older. The legacy adapter silently drops chunked cookies.onAuthStateChangereturning a promise. The callback is not awaited, so work inside it races the next render.- Service-role key with a
NEXT_PUBLIC_prefix. It ships to the browser.
Related tools. Read exp, sub, and role from the sb-…-auth-token cookie without a round trip with the JWT decoder, inspect the stored session JSON with the JSON formatter, and convert expires_at with the timestamp converter.
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesNext.js Server Actions: Swallowed Redirects and Body Limits
redirect() throws, so a try/catch swallows the navigation; the action body parser has a 1 MB limit; and useActionState cannot hold an Error. Fixes for all three.
Next.js Standalone in Docker: Missing CSS and sharp Module Errors
output standalone copies server.js only, so /_next/static and public are missing and every page renders unstyled. The image and copy fixes, plus the sharp native binding error.
Next.js 16 Upgrade: Async Params, proxy.ts, and Turbopack Build Breaks
The codemod gets you most of the way; the rest is async request APIs, a webpack config Turbopack refuses, and a renamed middleware file that silently stops running.
Next.js Hydration Mismatch: Why Server HTML Does Not Match the Client
React never reconciles a hydration mismatch; it re-renders the boundary. The four causes, the diff that finds them, and the patterns that keep the first client render identical to the server's.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.