A customer emails: “Your app keeps logging me out.” Your logs show AuthApiError: Invalid Refresh Token: Refresh Token Not Found, or the user just lands back on the login page with no message at all. Nothing looks broken in your code, and the AI tool that wrote it can’t reproduce the problem.
This error has a short list of causes, and you can sort them by asking one question: who gets logged out, and when? This guide turns that question into a decision tree. Each branch ends in one code or settings change and a prompt you can paste into Lovable, v0, Cursor or whichever tool built the app. Tool pages: /fix/supabase, /fix/lovable and /fix/v0. For an overview of every login error message in a Lovable app, see Lovable authentication errors.
What the error means
A Supabase session is two tokens. The access token is a JWT that proves who the user is; it is short-lived, and Supabase’s default lifetime is one hour. The refresh token is a random string that never expires on its own but works only once: the app trades it for a fresh pair of tokens, and the old one is spent (Supabase: User sessions). supabase-js performs that trade in the background because autoRefreshToken is on by default, so a normal browser app never writes refresh code itself.
“Refresh Token Not Found” comes back when the app presents a refresh token and Supabase Auth can’t find it in its database. Supabase’s server code returns this message, with code refresh_token_not_found and HTTP 400, when the token lookup comes back empty (Supabase Auth source: tokens/service.go). Sign-outs, password changes and detected token reuse all delete session rows, and the refresh tokens go with them (Supabase Auth source: models/sessions.go). So in plain words: the session this device was using has been deleted on the server. The useful question is what deleted it.
The same refresh endpoint has close relatives, and the exact wording tells you which cause you’re looking at. All of these come from the same server file:
| Message after “Invalid Refresh Token:” | code | What ended the session |
|---|---|---|
| Refresh Token Not Found | refresh_token_not_found | The session was deleted: a sign-out (possibly on another device), a password change on another device, or detected token reuse |
| Already Used | refresh_token_already_used | A spent token was presented again outside the reuse window; Supabase ends the whole session |
| Session Expired (Inactivity) | session_expired | The project’s inactivity timeout |
| Session Expired | session_expired | The project’s time-box (maximum session lifetime) |
| Session Expired (Revoked by Newer Login) | session_expired | “Single session per user” is on, and the user signed in somewhere else |
| No Valid Session Found | session_not_found | The token exists but its session doesn’t |
| User Banned | user_banned | You banned the user |
Supabase’s error code reference describes refresh_token_already_used as a revoked token used after the reuse interval, and session_expired as the result of an inactivity timeout or time-box setting (Supabase: Auth error codes).
Why the logout shows up later than the cause
Revoking a session doesn’t kill access tokens that were already issued. They keep working until the time in their exp claim (Supabase: Signing out). In supabase-js, a rejected refresh only clears the stored session if the access token has already expired; while it is still valid, the client keeps the session (supabase-js source: GoTrueClient.ts). With the default one-hour access token, a user can be signed out up to an hour after the event that caused it, which makes the logout look random.
Step 1: get the exact message
Your app may show only “Please sign in” or nothing at all. The precise wording is in the refresh response.
- In the browser. Open developer tools, go to the Network tab and filter by
auth/v1. Look for the request ending intoken?grant_type=refresh_token, which is how the client asks for a new pair (supabase-js source). Click the failed one and read thecodeandmessagein the response (older responses may usemsg). - In Supabase Logs. In the dashboard’s Logs page, pick Auth as the log type and filter Level to error. The User filter matches a user’s ID, so you can follow one customer’s report (Supabase: Logs). Retention depends on your plan, so check soon after the report comes in.
- In the Auth audit log. Supabase records sign-ins, sign-outs, password changes and token events. The actions to look for are
logout,user_updated_password,token_revokedandtoken_refreshed. If Write audit logs to the database is on, you can also query them with SQL fromauth.audit_log_entries(Supabase: Auth audit logs). - On a Next.js server. In an app built with v0 (or any Next.js app using
@supabase/ssr), the error may only appear in the server’s runtime logs, not in the browser. On Vercel, see Step 6 of the v0 deploy error guide for where those logs are. - On Lovable’s built-in backend. Go to More → Settings → Logs, then pick Authentication logs (Lovable: Logs).
A logout audit entry for the same user shortly before the failed refresh points to Branch A. A “Session Expired” message points to Branch B. An error that only appears in server logs of a Next.js app points to Branch C.
Step 2: the decision tree
Answer the question that matches what your users report:
- Signing out on one device logs the user out everywhere, or a password change logs them out elsewhere. Go to Branch A.
- Users are logged out after a fixed time, after being idle, or when they sign in on a second device. Go to Branch B.
- The app is built with Next.js (every new v0 chat starts as one) and the error shows up in server logs, with no pattern you can see. Go to Branch C.
If the user is bounced back to login straight after signing in, and the address bar shows localhost, that’s a redirect problem rather than a session problem: see Supabase auth redirecting to localhost.
Branch A: logged out on every device
Cause: signOut() defaults to signing out everywhere
In JavaScript, supabase.auth.signOut() with no options uses the global scope. That ends every session the user has, on every browser and device. The JavaScript, Swift, Python and C# libraries default to global; the Dart and Kotlin libraries use local unless told otherwise (Supabase: Signing out). Supabase’s sign-out page now warns about this exact symptom: the other devices hit “Refresh Token Not Found” on their next refresh even though nobody signed out on them. Its server-side auth guide also names a signOut() call with no scope as a common cause of invalid refresh token errors on the server (Supabase: Advanced SSR guide).
The three scopes (Supabase: JavaScript signOut reference):
global(the default): ends all of the user’s sessions.local: ends only the session on this device.others: ends every session except the current one. This is what a “Sign out of all other devices” button should call.
One extra detail from the reference: with local, the session on the device is cleared first and the server call is best effort. With global, if the server call fails, the device stays signed in and the error is returned.
Cause: a password change
When a signed-in user changes their password, Supabase Auth keeps the session they changed it from and deletes all their other sessions. When the password is updated without a session attached, the code removes every session the user has (Supabase Auth source: models/user.go). Supabase’s Sessions page lists a password change among the events that end a session. This is intended behaviour: after a reset, the other devices should have to sign in again. Look for user_updated_password in the audit log to confirm it. If the reset link itself fails, see Supabase reset password not working.
Deleting a user also ends their sessions (Lovable: Users and authentication), so “Refresh Token Not Found” right after an account deletion is expected.
The change
Search the codebase for signOut(. Every place that handles an ordinary “Log out” button should pass the scope:
// Before: ends every session this user has, on every device
await supabase.auth.signOut()
// After: ends only the session on this device
await supabase.auth.signOut({ scope: 'local' })
The same applies to server code, such as a Next.js route handler or server action that signs the user out with a server client.
Prompt for your AI tool
Users are logged out on all their devices when they sign out on one.
Supabase signOut() defaults to the global scope. Find every call to
supabase.auth.signOut() in the project. For the normal "Log out" button,
change it to supabase.auth.signOut({ scope: 'local' }). If there is a
"Sign out of all other devices" option, use { scope: 'others' } there.
Leave auth settings, RLS policies and API keys alone. List each file you
changed.
Branch B: logged out after a set time
Cause: session limits in your Supabase Auth settings
By default a Supabase session has no end date, and one user can hold any number of sessions. Supabase offers three optional controls in the project’s Auth settings, which the Sessions docs mark as a Pro-plan-and-up feature (Supabase: User sessions):
- Time-box user sessions: a fixed maximum lifetime, after which the user must sign in again.
- Inactivity timeout: ends sessions that haven’t refreshed within the set duration.
- Single session per user: keeps only the most recently active session and ends the rest.
If one of these is the cause, the refresh error says “Session Expired”, “Session Expired (Inactivity)” or “Session Expired (Revoked by Newer Login)”, not “Refresh Token Not Found”. That difference is the quickest way to rule this branch in or out.
Two details from the Sessions page explain odd timing. Supabase doesn’t end sessions the moment a limit is reached; it checks at the next refresh. So the real logout time is the configured limit plus up to one access-token lifetime. And changing these settings doesn’t end existing sessions on the spot; the new rule applies at each session’s next refresh.
Also check the access-token expiry under Auth settings → Sessions. Supabase recommends the default of one hour, advises against going above it, and warns that values under five minutes cause trouble, including clock-skew errors that are hard to debug.
On Lovable’s built-in backend there are no session-length, inactivity or token-expiry settings at all (Lovable: Users and authentication). If users there are logged out on a schedule, the cause is in the app’s code, not in a setting.
If the “set time” is about a day and the app runs on Next.js, read Branch C before touching any setting. The developer who opened the main GitHub thread on this error saw it roughly once a day in a Next.js app, with no session limits involved (supabase/ssr issue #68).
The change
Decide whether the limit is something you want. If you didn’t mean to set it, clear or relax it in Auth settings. If you need it (for compliance, say), keep it, and make the app explain the logout instead of failing silently: see Handle the error so users aren’t confused below.
Prompt for your AI tool
Our Supabase project uses a session time-box / inactivity timeout on purpose.
When the session ends, the refresh fails with code "session_expired" and the
user lands on a broken page. Add handling so that when the Supabase client
reports SIGNED_OUT, or getSession() returns an error with code
"session_expired" or "refresh_token_not_found", the app clears the local
session with signOut({ scope: 'local' }) and sends the user to /login with
the message "Your session ended. Please sign in again." Do not change
Supabase auth settings. Describe your plan first, then make the change.
Branch C: only in a Next.js or v0 app
In a browser-only app, one copy of supabase-js owns the session and refreshes it. In a Next.js app using @supabase/ssr, the session lives in cookies, and both the server and the browser can refresh it. That’s two refreshers for one single-use token. Every new v0 chat starts as a Next.js app (v0: Design Systems 2.0), so this branch applies to v0 builds that use Supabase Auth. Check package.json: if next and @supabase/ssr are both there, read on.
Supabase’s Next.js setup gives one file, the Proxy (called Middleware before Next.js 16), three jobs: refresh the session by calling supabase.auth.getClaims(), hand the new cookies to Server Components, which then have no reason to refresh again, and send the new cookies to the browser so it stops holding the old token (Supabase: Creating a Supabase client for SSR). The failures below each break one of those jobs.
Check 1: the Proxy or Middleware file never runs
Next.js 16 deprecated the middleware file convention and renamed it to proxy (Next.js: proxy.js). Supabase’s guide points out the trap: a proxy.ts file does nothing on Next.js 15 or older, so sessions never refresh on the server and users get signed out. Compare the next version in package.json with the file:
- Next.js 16 or later:
proxy.tsexportingasync function proxy(request). - Next.js 15 or earlier:
middleware.tsexportingasync function middleware(request).
The Supabase code inside is the same in both. Also check the file’s matcher: if it excludes your app’s pages, the refresh never runs for them.
Check 2: the Proxy returns a response without the new cookies
Supabase’s updateSession helper builds a supabaseResponse that carries the refreshed cookies. If your code returns something else (a redirect, a rewrite, a response from an i18n library), the browser never receives the new tokens. It keeps sending the spent refresh token, and the session dies on a later request. Supabase’s guide is explicit that the earlier response doesn’t carry the cookies.
// Inside updateSession, after supabase.auth.getClaims():
// Wrong: a fresh response drops the refreshed cookies
// return NextResponse.redirect(url)
// Right: copy the cookies and cache headers onto any other response
const redirect = NextResponse.redirect(url)
redirect.cookies.setAll(supabaseResponse.cookies.getAll())
for (const header of ['cache-control', 'expires', 'pragma']) {
const value = supabaseResponse.headers.get(header)
if (value) redirect.headers.set(header, value)
}
return redirect
The cache headers matter for a second reason. Supabase’s SSR guide warns that a CDN which caches a response carrying a refreshed Set-Cookie can hand one user’s session to another. Since version 0.10.0, @supabase/ssr hands Cache-Control, Expires and Pragma to your setAll handler for this purpose (Supabase: Advanced SSR guide).
Check 3: extra code, or the wrong call, in the Proxy
Supabase’s example code warns against running anything between createServerClient and supabase.auth.getClaims(), and says removing getClaims() can cause random logouts. In server code, use getClaims() to check who the user is. getSession() trusts the cookie without verifying it, which Supabase says not to rely on in the Proxy.
Check 4: an old @supabase/ssr and two refreshes per request
In the main GitHub thread, the Supabase maintainer assigned to it traced the originally reported bug to a background session start-up in the server client that raced the app’s own getUser()/getSession() call. In September 2026 they wrote that it “was fixed in @supabase/ssr@0.8.1 via skipAutoInitialize” (supabase/ssr issue #68). They put most later reports in that thread down to concurrent refreshes, where a browser tab and the server refresh the same session at once, and their advice was not to call getUser(), getClaims() or getSession() in both the Proxy and an API route for the same request.
Hosted Supabase allows a spent refresh token to be presented again within a short reuse interval, 10 seconds by default, partly to cover server rendering, where the server and then the browser use the same token (Supabase: User sessions). Outside that window, reuse ends the session: the request that loses gets “Already Used”, and the session is deleted, so the other side’s next refresh gets “Refresh Token Not Found” (Supabase Auth source: tokens/service.go). The maintainer also noted that self-hosted Supabase leaves this window off by default, and suggested giving GOTRUE_SECURITY_REFRESH_TOKEN_REUSE_INTERVAL a small value of several seconds there.
The change
Upgrade @supabase/ssr and @supabase/supabase-js to current releases, then make the Proxy match Supabase’s current Next.js example: correct file name for your Next.js version, getClaims() straight after createServerClient, and supabaseResponse (or a copy with its cookies and cache headers) as the only thing it returns.
Prompt for v0 or your AI tool
Users of this Next.js app are randomly logged out, and the server logs show
"AuthApiError: Invalid Refresh Token: Refresh Token Not Found".
1. Check the Next.js version in package.json. On Next.js 16+, the session
refresh must live in proxy.ts exporting proxy(); on 15 or earlier, in
middleware.ts exporting middleware(). Fix the file name if it is wrong.
2. Make updateSession match Supabase's current Next.js SSR example: call
supabase.auth.getClaims() immediately after createServerClient, apply the
headers passed to setAll, and return supabaseResponse. If any branch
returns a redirect or another response, copy supabaseResponse's cookies
and its Cache-Control, Expires and Pragma headers onto it first.
3. Make sure no request calls getUser/getClaims/getSession in both the proxy
and an API route.
4. Upgrade @supabase/ssr and @supabase/supabase-js to their latest versions.
Do not change Supabase auth settings or RLS. Show me the diff before applying.
Handle the error so users aren’t confused
Whatever the cause, some sessions will end, so the app should handle it cleanly: clear what’s stored on the device and show the login page with a short explanation. It should not loop, show a raw error, or leave a half-loaded dashboard.
In a browser-only app, such as one of Lovable’s older React + Vite projects, listen for the sign-out event once, near the root of the app:
supabase.auth.onAuthStateChange((event) => {
// Fires for deliberate sign-outs and for sessions that ended on the server
if (event === 'SIGNED_OUT') {
window.location.assign('/login?reason=session-ended')
}
})
Keep that callback synchronous. The supabase-js source marks async callbacks as deprecated, because one that triggers a nested refresh can deadlock (supabase-js source). Then, on the login page, show “Your session ended. Please sign in again.” when reason=session-ended is in the URL.
If you read the session yourself on startup, treat the session-ending codes as a sign-out:
const { error } = await supabase.auth.getSession()
if (error && ['refresh_token_not_found', 'refresh_token_already_used',
'session_expired', 'session_not_found'].includes(error.code ?? '')) {
await supabase.auth.signOut({ scope: 'local' }) // clears this device only
window.location.assign('/login?reason=session-ended')
}
Note the local scope here: a global sign-out in an error handler would end the user’s sessions on every other device too, which is Branch A all over again.
In Next.js, Supabase’s example Proxy redirects to /login when getClaims() returns no user; add the same reason parameter there. Supabase’s SSR guide suggests that when the server hits an invalid refresh token, rendering can be left to the browser, since the client library there holds the current token.
Mistakes that make it worse
- Don’t turn off refresh token reuse detection. The option exists in the Advanced section of the Auth settings, but Supabase’s Sessions page calls disabling it “generally not recommended”. It exists to limit the damage if a refresh token leaks, for example through logs that capture cookies or request bodies. Turning it off hides Branch C instead of fixing it.
- Don’t change the reuse interval on a hosted project. Supabase advises leaving the 10-second default alone.
- Don’t raise the access-token expiry to hide logouts. A longer JWT lifetime only delays the logout, and Supabase discourages going past one hour.
- Don’t shorten the lifetime of the auth cookies. Supabase’s SSR guide says a short cookie lifetime only makes the experience worse, and the Sessions page recommends letting Supabase Auth, not the browser, decide when a session ends.
- Don’t let the AI wrap the refresh in a retry loop. A deleted session stays deleted. Retrying the same token only fills your logs.
FAQ
Why does signing out on my phone log me out on my laptop?
Your app calls supabase.auth.signOut() with no options, and in JavaScript that means global: every session the user has is ended. The laptop keeps working until its access token expires, then its refresh fails with “Refresh Token Not Found”. Pass { scope: 'local' } for an ordinary log-out button.
Is “Invalid Refresh Token” a security problem?
On its own, no. It tells you a session ended, and the causes above are normal app behaviour or setup mistakes. The related “Already Used” message comes from reuse detection, which Supabase built to guard against stolen refresh tokens. If you see “Already Used” for users whose pattern doesn’t fit Branch C, review where tokens could leak, such as logs that record cookies, request bodies or URL parameters.
Do Lovable apps have the Next.js cookie problem?
It depends on the project’s stack. Older Lovable projects are React + Vite apps that build pages in the browser, where one client holds and refreshes the session, so Branch C doesn’t apply to them. Since May 13, 2026, new Lovable projects use TanStack Start, which renders pages on the server (Lovable: Upgrade a project to TanStack Start). Ask Lovable “What stack is this project on?”, then check whether the code creates a server client with createServerClient from @supabase/ssr. If it does, the same single-use token rules apply on the server, and the Branch C checks for returning refreshed cookies are worth doing.
Which version of @supabase/ssr fixed the middleware race?
In supabase/ssr issue #68, the Supabase maintainer assigned to the thread wrote in September 2026 that the original race “was fixed in @supabase/ssr@0.8.1 via skipAutoInitialize”. Earlier, in February 2026, the same maintainer had pointed the thread to a release candidate, 0.9.0-rc.6. The issue was closed on September 8, 2026. Either way, upgrade to the current release; the maintainer also said that most later reports in the thread were concurrent refreshes, which Check 4 covers.
How long does a Supabase session last?
Until a sign-out or one of the events above ends it: by default, Supabase sessions have no maximum age. The access token inside the session lasts one hour by default and is renewed automatically. On your own Supabase project you can add a time-box, an inactivity timeout or a single-session rule in Auth settings. Lovable’s built-in backend has none of these settings.
Comments