Supabase "AuthSessionMissingError: Auth session missing!": find where the session went
By AI App Medic · Updated · Supabase · Auth · Next.js · Lovable
Somewhere in your app a Supabase auth call fails and the console shows:
AuthSessionMissingError: Auth session missing!
at GoTrueClient._getUser (...)
{ name: "AuthSessionMissingError", status: 400, code: undefined }
The status 400 is misleading. In most cases nothing was sent to Supabase at all. Methods that act for the signed-in user, such as getUser(), updateUser(), refreshSession() and reauthenticate(), first look for a stored session. When there is none, supabase-js raises this error itself. The question to answer is not "why is Supabase broken" but "why is there no session in this place at this moment".
AI builders hit this a lot because they generate auth code in several places at once: a browser client, a server client, a reset page, an Edge Function. Each of those has its own idea of where the session lives. Five cases cover almost every report.
Step 1: find which call throws
Search the code for the auth calls and log the method with the error, so you know which case you are in:
const { data, error } = await supabase.auth.getUser();
if (error) console.error("getUser on", location.pathname, error.name, error.message);
getUser()in the browser on a public page: case 1.updateUser({ password })on a reset or change password page: case 2.getUser()in a Next.js server component, route handler, server action or middleware: case 3.getUser()inside a Supabase Edge Function: case 4.- Any call that used to work for a user who was signed in and now fails: case 5.
Case 1: nobody is signed in, and that is fine
A header that decides between "Sign in" and "My account" calls getUser() on every page. For a visitor, the error is the correct answer. The bug is code that treats it as a failure and shows a red toast to everyone who is not logged in. Let it through:
import { isAuthSessionMissingError } from "@supabase/supabase-js";
const { data: { user }, error } = await supabase.auth.getUser();
if (error && !isAuthSessionMissingError(error)) {
throw error; // a real problem: network, bad key, server error
}
// user === null means signed out: show the public view
If you only need to know whether a session exists in the browser, for example to choose which button to show, getSession() returns session: null without an error. For anything that grants access, keep using getUser() or getClaims(), which check the token, and enforce access with row level security in the database.
Case 2: the reset password page has no session
This is the most common report. The user clicks the link in the reset email, lands on your "choose a new password" page, submits the form, and updateUser({ password }) fails with Auth session missing. updateUser() only works for a signed-in user, and on that page the only possible session is the one the email link should have created. Usual reasons it did not:
- The link was opened in another browser or device. With the PKCE flow, which
@supabase/ssralways uses, requesting the email stores a code verifier in the browser that asked. Only that browser can turn the?code=link into a session. Ask for the reset on a laptop, open the email on a phone, and there is no session. - The page never exchanges the link. The email points to your page with a
codeortoken_hashin the URL, but nothing on the page callsexchangeCodeForSession()orverifyOtp(). AI-generated reset pages often render the form straight away and skip this step. - The link was already used or expired. Email security scanners in company mailboxes open links before the person does, and links expire after an hour by default. See Supabase "Email link is invalid or has expired".
- The link sent the user to the wrong site, such as
localhostor the preview URL, so the session landed somewhere else. See Supabase login redirects to localhost.
The setup that works on any device is a token hash link handled by your own page. In Authentication, Email Templates, Reset Password, change the link to:
<a href="{{ .SiteURL }}/auth/reset?token_hash={{ .TokenHash }}&type=recovery">Reset your password</a>
Make sure /auth/reset on your real domain is in the Redirect URLs list. On that page, turn the hash into a session first. Do it when the user clicks a button rather than on page load, so a mail scanner that opens the link does not use it up:
const params = new URLSearchParams(window.location.search);
async function continueReset() {
const { error } = await supabase.auth.verifyOtp({
token_hash: params.get("token_hash"),
type: "recovery",
});
if (error) {
showMessage("This link has expired or was already used. Request a new one.");
return;
}
showNewPasswordForm(); // now updateUser({ password }) has a session
}
If you keep the default link, handle the session the link creates before showing the form. With the implicit flow the client picks the session up from the URL and fires a PASSWORD_RECOVERY event:
supabase.auth.onAuthStateChange((event) => {
if (event === "PASSWORD_RECOVERY") showNewPasswordForm();
});
With PKCE and a ?code= link, call supabase.auth.exchangeCodeForSession(code) on the page or in a route handler first. Either way, check for a session before rendering the form. A form that can only fail is worse than a clear "request a new link" message.
Case 3: the server cannot see the browser's session
In a Next.js app built with v0 or Cursor, the user is signed in on the client, but a server component, server action or route handler gets Auth session missing. The server only sees what arrives with the request, which means cookies. Two mistakes cause this:
- The browser client stores the session in localStorage.
createClient()from@supabase/supabase-jsin the browser saves the session in localStorage by default. The server never receives localStorage, so every server-sidegetUser()finds nothing. - The server client was created without the request cookies, or with a plain
createClient()on the server, which starts with an empty session.
Use the @supabase/ssr helpers on both sides. In the browser:
// lib/supabase/client.ts
import { createBrowserClient } from "@supabase/ssr";
export const createClient = () =>
createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
On the server, with the cookies of the current request:
// lib/supabase/server.ts
import { createServerClient } from "@supabase/ssr";
import { cookies } from "next/headers";
export async function createClient() {
const cookieStore = await cookies();
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll: () => cookieStore.getAll(),
setAll: (list) => {
try {
list.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options));
} catch {
// called from a server component; middleware refreshes the cookies
}
},
},
}
);
}
Server components cannot write cookies, so the session must be refreshed in middleware, as in the Supabase Next.js guide. On Next.js 16 that file is called proxy.ts instead of middleware.ts. If the file is missing, sits in the wrong folder (it belongs next to app/, inside src/ if you use one), or its matcher skips the routes that read the user, sessions expire on the server after an hour and the error starts appearing for users who are still "logged in" in the browser.
After switching to cookie storage, existing users have to sign in once more, because their old session is still in localStorage. Also check that fetch calls from the browser to your own API go to the same domain, since cookies are not sent to a different origin unless you set credentials: "include" and matching CORS headers.
Case 4: an Edge Function calls getUser() with no token
Inside a Supabase Edge Function you create a new client. That client has no stored session, so supabase.auth.getUser() with no argument fails with Auth session missing, even when the browser sent a valid token. Read the token from the request and pass it in:
import { createClient } from "npm:@supabase/supabase-js@2";
Deno.serve(async (req) => {
const authHeader = req.headers.get("Authorization") ?? "";
const token = authHeader.replace("Bearer ", "");
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_ANON_KEY")!,
{ global: { headers: { Authorization: authHeader } } }
);
const { data: { user }, error } = await supabase.auth.getUser(token);
if (error || !user) {
return new Response(JSON.stringify({ error: "Not signed in" }), { status: 401 });
}
// queries through this client now run as the user, with RLS applied
});
The global.headers part makes database queries from the function run as the user, so row level security still applies. On the calling side, supabase.functions.invoke() attaches the user's token automatically when the user is signed in. A plain fetch() does not, so add the header yourself. If the function answers 401 before your code runs, the problem is the JWT check at the gateway instead, covered in Supabase Edge Function 401 Invalid JWT.
Case 5: the session was ended on the server
When the token in the browser points to a session that no longer exists in Supabase, the server answers session_not_found, supabase-js removes the stored session, and the next call reports Auth session missing. That happens when the user signed out on another device with global scope, the user was deleted, an admin revoked their sessions, or a session time limit or inactivity timeout in your auth settings ran out. The right response is to send the user to sign in again:
supabase.auth.onAuthStateChange((event, session) => {
if (event === "SIGNED_OUT" || !session) {
clearUserState();
router.replace("/login");
}
});
If this happens to many users at once right after a deploy, look for a change to the Supabase URL or keys, a new project, or code that calls signOut() on load. Refresh token errors that show up next to this one are covered in Invalid Refresh Token: Refresh Token Not Found.
What not to do
Do not "fix" the error by creating the client with the service role key, by skipping the user check in an Edge Function, or by passing a user id from the browser and trusting it. All three make the error go away by removing authentication. If an AI prompt produced one of those changes, revert it and apply the fix for your case above.
Prevention
Pick one place where the session lives and use it everywhere: cookies through @supabase/ssr for Next.js, the default client for a single page app. Create the Supabase client once per side, not in every component. Test the reset flow by requesting the email in one browser and opening it in another, and test it with a link that is more than an hour old. Test every server route and Edge Function with a signed-out request and a signed-in one. Handle the signed-out state on public pages deliberately, so a missing session is a normal branch in the code and not an error message.
FAQ
What does Auth session missing mean in Supabase?
It means supabase-js looked for a signed-in session and found none at the moment the call ran. In most cases the check happens inside the library before any request reaches Supabase, so it is not an outage and not a bad API key.
Why does getUser() return Auth session missing for visitors?
Because nobody is signed in on that browser. For a public page that is the correct answer. Check the error with isAuthSessionMissingError(error) and show the logged-out view instead of an error toast.
Why does updateUser fail with Auth session missing on my reset password page?
updateUser() needs a signed-in user, and on a reset page that session has to come from the link in the email. If the link was opened in a different browser than the one that asked for the reset, was already used, expired, or your page never calls verifyOtp() or exchangeCodeForSession(), there is no session and the call fails.
Why does my Next.js server action say Auth session missing when the user is logged in?
The browser stored the session in localStorage, which the server cannot read, or the server client was created without the request cookies. Use createBrowserClient and createServerClient from @supabase/ssr so the session is kept in cookies and both sides see it.
How do I get the user in a Supabase Edge Function without this error?
Read the Authorization header from the request, strip the Bearer prefix and call supabase.auth.getUser(token). Calling getUser() with no argument inside the function looks for a stored session, and a fresh client in the function has none.
Is it safe to ignore AuthSessionMissingError?
Only where a missing session is a normal state, such as a public page checking whether to show Sign in. On a page that requires login, redirect to the login page. Do not work around it with the service role key, which skips the user check entirely.
Related guides
- Supabase "Email link is invalid or has expired": why the link dies before the user clicks it
- Supabase AuthApiError: Invalid Refresh Token: Refresh Token Not Found
- Supabase Edge Function returns 401 "Invalid JWT": find who rejected the call and fix it
- Supabase "JWT expired" (PGRST303 or PGRST301): why it starts after an hour and how to fix it
- Supabase "AuthApiError: Invalid login credentials" when the user and password look right