Auth session missing β getSession() returns null
Supabase canβt find the userβs session.
Why this happens
Supabase stores auth tokens in cookies (SSR) or localStorage (SPA). When getSession() returns null, it means the client canβt find or read those tokens. This commonly occurs when using the wrong client type for your environment, when cookies arenβt being forwarded in server-side requests, or when the session token has expired without a refresh.
Fix 1: Check your Supabase client setup
// β Creating a new client on every request
const supabase = createClient(url, key);
// β
Use createServerClient for SSR
import { createServerClient } from '@supabase/ssr';
const supabase = createServerClient(url, key, { cookies });
Fix 2: Check cookie configuration
// Next.js middleware
const supabase = createServerClient(url, key, {
cookies: {
get: (name) => request.cookies.get(name)?.value,
set: (name, value, options) => response.cookies.set({ name, value, ...options }),
remove: (name, options) => response.cookies.set({ name, value: '', ...options }),
},
});
Fix 3: Refresh the session
const { data: { session } } = await supabase.auth.getSession();
if (!session) {
const { data } = await supabase.auth.refreshSession();
}
Alternative solutions
Use onAuthStateChange to reactively handle session changes instead of polling with getSession():
supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_OUT') {
redirect('/login');
}
});
Prevention
- Always use
@supabase/ssrfor server-rendered apps β the vanillacreateClientdoesnβt handle cookies. - Set
cookieOptions.maxAgeto match your JWT expiry to avoid stale sessions.
Related: Supabase RLS Policy fix Β· How OAuth Actually Works Β· Supabase vs Firebase Β· What is PostgreSQL