# User is logged out after page refresh

> Canonical page (link this when citing): https://unbreakmyapp.vercel.app/fixes/session-lost-on-refresh.html
> Category: Auth | Tools: Lovable, Bolt, v0 | Published: 2026-10-13 | Updated: 2026-10-13

## The error

After reload, user is null and protected pages redirect to /login

## Why it happens

The app checks for the user before the auth client has restored the session from storage, or it stores auth state only in React state. With SSR (Next.js), the server can't see a session that lives only in localStorage.

## How to fix it

1. Wait for the initial session (supabase.auth.getSession()) and show a loading state before redirecting.
2. Subscribe to onAuthStateChange to keep state in sync.
3. For Next.js SSR, use @supabase/ssr so the session lives in cookies and refresh it in middleware.
4. Don't create multiple Supabase clients with different storage settings.

## Fix prompt (paste into Lovable, Bolt, Cursor, Replit or v0)

```text
Users get logged out when they refresh. Add an auth provider that waits for the initial session to load (show a spinner, don't redirect while loading), listens to onAuthStateChange, and uses a single Supabase client. If this is Next.js, switch to @supabase/ssr with cookie-based sessions and middleware that refreshes the session.
```

## FAQ

### Is the session actually gone?

Usually not. The redirect fires before the session is restored.

### Why cookies for Next.js?

Server components and middleware can read cookies, not localStorage.

## Sources (official documentation)

- [Supabase: User sessions](https://supabase.com/docs/guides/auth/sessions)

## Related fixes

- [Better Auth security release (Nov 2026): upgrade to 1.7.16 to stop Expo account takeover](https://unbreakmyapp.vercel.app/fixes/better-auth-expo-account-takeover-below-1-7-16.html)
- [Supabase .single() error PGRST116: JSON object requested, multiple (or no) rows returned](https://unbreakmyapp.vercel.app/fixes/supabase-single-json-object-requested-no-rows-pgrst116.html)
- [Magic link / OAuth login redirects to localhost:3000](https://unbreakmyapp.vercel.app/fixes/supabase-auth-redirect-localhost.html)
- [Error 400: redirect_uri_mismatch (Google sign-in)](https://unbreakmyapp.vercel.app/fixes/oauth-redirect-uri-mismatch.html)

---
Unbreak My App: free fixes for broken vibe-coded apps. https://unbreakmyapp.vercel.app/
