|
| 1 | +--- |
| 2 | +title: Manage Auth Sessions Correctly |
| 3 | +impact: CRITICAL |
| 4 | +impactDescription: Session mismanagement causes auth failures, security issues, and poor UX |
| 5 | +tags: auth, sessions, tokens, refresh, onAuthStateChange, jwt |
| 6 | +--- |
| 7 | + |
| 8 | +## Manage Auth Sessions Correctly |
| 9 | + |
| 10 | +Session lifecycle, token refresh, and auth state listeners. |
| 11 | + |
| 12 | +## Session Structure |
| 13 | + |
| 14 | +```typescript |
| 15 | +interface Session { |
| 16 | + access_token: string // JWT, expires in 1 hour (default) |
| 17 | + refresh_token: string // Single-use, used to get new access_token |
| 18 | + expires_at: number // Unix timestamp when access_token expires |
| 19 | + expires_in: number // Seconds until expiration |
| 20 | + user: User // User object with id, email, metadata |
| 21 | +} |
| 22 | +``` |
| 23 | + |
| 24 | +## Listen to Auth State Changes |
| 25 | + |
| 26 | +`onAuthStateChange` is the single source of truth for auth state. In React, wrap it with `useSyncExternalStore` for safe, tear-free subscriptions: |
| 27 | + |
| 28 | +```typescript |
| 29 | +import { useSyncExternalStore } from 'react' |
| 30 | + |
| 31 | +let currentSession: Session | null = null |
| 32 | + |
| 33 | +function subscribe(callback: () => void) { |
| 34 | + const { data: { subscription } } = supabase.auth.onAuthStateChange( |
| 35 | + (_event, session) => { |
| 36 | + currentSession = session |
| 37 | + callback() |
| 38 | + } |
| 39 | + ) |
| 40 | + return () => subscription.unsubscribe() |
| 41 | +} |
| 42 | + |
| 43 | +function getSnapshot() { |
| 44 | + return currentSession |
| 45 | +} |
| 46 | + |
| 47 | +// In your component |
| 48 | +function useSession() { |
| 49 | + return useSyncExternalStore(subscribe, getSnapshot) |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +### Auth Events |
| 54 | + |
| 55 | +| Event | When Fired | |
| 56 | +|-------|------------| |
| 57 | +| `INITIAL_SESSION` | Right after client is constructed and initial session from storage is loaded | |
| 58 | +| `SIGNED_IN` | User signed in successfully | |
| 59 | +| `SIGNED_OUT` | User signed out | |
| 60 | +| `TOKEN_REFRESHED` | Access token was refreshed | |
| 61 | +| `USER_UPDATED` | User profile was updated | |
| 62 | +| `PASSWORD_RECOVERY` | User clicked password reset link | |
| 63 | + |
| 64 | +## Get Current Session |
| 65 | + |
| 66 | +```typescript |
| 67 | +// From local storage (fast, but not validated) |
| 68 | +const { data: { session } } = await supabase.auth.getSession() |
| 69 | + |
| 70 | +// Validate on server: getClaims() validates JWT locally (fast, preferred with asymmetric keys) |
| 71 | +const { data: claims } = await supabase.auth.getClaims() |
| 72 | + |
| 73 | +// Or use getUser() which round-trips to Auth server (always accurate) |
| 74 | +const { data: { user } } = await supabase.auth.getUser() |
| 75 | +``` |
| 76 | + |
| 77 | +## Common Mistakes |
| 78 | + |
| 79 | +### 1. Using getSession() for Server-Side Validation |
| 80 | + |
| 81 | +**Incorrect:** |
| 82 | + |
| 83 | +```typescript |
| 84 | +// Server-side code |
| 85 | +const { data: { session } } = await supabase.auth.getSession() |
| 86 | +// DANGER: getSession reads from storage, doesn't validate JWT |
| 87 | +const userId = session?.user.id |
| 88 | +``` |
| 89 | + |
| 90 | +**Correct:** |
| 91 | + |
| 92 | +```typescript |
| 93 | +// Server-side code - always use getClaims() which validates the JWT |
| 94 | +const { data, error } = await supabase.auth.getClaims() |
| 95 | +if (error || !data) { |
| 96 | + return unauthorizedResponse() |
| 97 | +} |
| 98 | +const userId = data.claims.sub |
| 99 | +``` |
| 100 | + |
| 101 | +> **Asymmetric JWTs:** Asymmetric JWT signing keys are the recommended approach. Symmetric signing is not recommended for production. With asymmetric keys, `getClaims()` verifies tokens locally via WebCrypto with no network request, significantly faster than `getUser()` which always round-trips to the Auth server. |
| 102 | +
|
| 103 | +### 2. Calling Supabase in onAuthStateChange Without Deferring |
| 104 | + |
| 105 | +**Incorrect:** |
| 106 | + |
| 107 | +```typescript |
| 108 | +supabase.auth.onAuthStateChange(async (event, session) => { |
| 109 | + // This can cause deadlocks |
| 110 | + await supabase.from('profiles').select('*') |
| 111 | +}) |
| 112 | +``` |
| 113 | + |
| 114 | +**Correct:** |
| 115 | + |
| 116 | +```typescript |
| 117 | +supabase.auth.onAuthStateChange((event, session) => { |
| 118 | + // Defer Supabase calls with setTimeout |
| 119 | + setTimeout(async () => { |
| 120 | + await supabase.from('profiles').select('*') |
| 121 | + }, 0) |
| 122 | +}) |
| 123 | +``` |
| 124 | + |
| 125 | +### 3. Not Unsubscribing from Auth Listener |
| 126 | + |
| 127 | +**Incorrect:** |
| 128 | + |
| 129 | +```typescript |
| 130 | +useEffect(() => { |
| 131 | + supabase.auth.onAuthStateChange((event, session) => { |
| 132 | + setUser(session?.user) |
| 133 | + }) |
| 134 | + // Missing cleanup - causes memory leaks |
| 135 | +}, []) |
| 136 | +``` |
| 137 | + |
| 138 | +**Correct:** |
| 139 | + |
| 140 | +```typescript |
| 141 | +useEffect(() => { |
| 142 | + const { data: { subscription } } = supabase.auth.onAuthStateChange( |
| 143 | + (event, session) => { |
| 144 | + setUser(session?.user ?? null) |
| 145 | + } |
| 146 | + ) |
| 147 | + |
| 148 | + return () => subscription.unsubscribe() |
| 149 | +}, []) |
| 150 | +``` |
| 151 | + |
| 152 | +## JWT Claims |
| 153 | + |
| 154 | +Access user claims in RLS policies: |
| 155 | + |
| 156 | +```sql |
| 157 | +-- Get user ID |
| 158 | +auth.uid() -- Returns UUID |
| 159 | + |
| 160 | +-- Get full JWT |
| 161 | +auth.jwt() -- Returns JSONB |
| 162 | + |
| 163 | +-- Get specific claims |
| 164 | +auth.jwt() ->> 'email' -- User email |
| 165 | +auth.jwt() -> 'app_metadata' ->> 'role' -- Custom role (admin-set) |
| 166 | +auth.jwt() ->> 'aal' -- Auth assurance level (aal1/aal2) |
| 167 | +``` |
| 168 | + |
| 169 | +## Related |
| 170 | + |
| 171 | +- [core-signin.md](core-signin.md) - Sign-in flows |
| 172 | +- [server-ssr.md](server-ssr.md) - Server-side session handling |
| 173 | +- [Docs: Sessions](https://supabase.com/docs/guides/auth/sessions) |
| 174 | +- [Docs: onAuthStateChange](https://supabase.com/docs/reference/javascript/auth-onauthstatechange) |
0 commit comments