Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readNext.js
#Next.js#Supabase#Authentication#Cookies
3D illustration of a cookie jar and an auth token slab being split between a server cube and a browser cube, a locked padlock between them

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.

ts
// 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.

ts
// 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

ConcernNext.js 14Next.js 15Next.js 16
cookies()synchronousPromise, must awaitsame as 15
Interception filemiddleware.ts, edgemiddleware.ts, edge or nodeproxy.ts, node only
Exported functionmiddlewaremiddlewareproxy
Cookie write in a renderthrowsthrowsthrows
Cookie adapterWorks in a renderPersists the refreshTypical failure
getAll / setAllyes, writes skippedyes, via proxynone when the proxy returns its response
get / set / removepartlyunreliabledrops …-auth-token.1 chunks
Omitted entirelyreads documentnevernull user every request
Two clients per requestyesnoNavigatorLockAcquireTimeoutError

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.

ts
const { data: { user } } = await (await createClient()).auth.getUser(); if (!user) redirect("/login"); // redirect, never a manual cookie delete

2. Reading the signed-out loop instead of guessing

The loop has three breakages and one log line separates them:

ts
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.

ts
// 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.

ts
"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

ts
// 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.

ts
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() without await. It returns a Promise in Next.js 15 and 16; the adapter then calls .getAll() on a Promise, and the failure surfaces far away as Cannot read properties of undefined.
  • One client per render. createBrowserClient in a component body subscribes anew every render. Use a module-level singleton or useState.
  • middleware.ts left on Next.js 16. It runs, but runtime in 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/ssr 0.4 and older. The legacy adapter silently drops chunked cookies.
  • onAuthStateChange returning 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 tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.