React Web App - Auth getSession & getUser doesn't fetch on browser. regaining focus after lost focus

React Web App - All is okay when the app starts but when the browser looses focus & again regains focus, await supabase.auth.getSession() does not return session & supabase.auth.getUser() doesn't return user. If I refresh the page then all data loads nicely. Here is the code of Onload of user Token Wallet Page which fetches user token data from database. const getCurrentUserId = async (): Promise<string | null> => { console.log('Getting current user ID...'); // First try getSession (reads from localStorage, fast) try { const sessionPromise = supabase.auth.getSession(); const sessionTimeout = new Promise((, reject) => setTimeout(() => reject(new Error('Session timeout')), 2000) ); const { data: { session } } = await Promise.race([sessionPromise, sessionTimeout]) as any; if (session?.user?.id) { console.log('Got user from session'); cachedUserId.current = session.user.id; return session.user.id; } } catch (error) { console.log('Session check failed:', error); } // Fallback to getUser (may trigger network request) try { const userPromise = supabase.auth.getUser(); const userTimeout = new Promise((, reject) => setTimeout(() => reject(new Error('User timeout')), 5000) ); const { data: { user } } = await Promise.race([userPromise, userTimeout]) as any; if (user?.id) { console.log('Got user from getUser'); cachedUserId.current = user.id; return user.id; } } catch (error) { console.log(' User check failed:', error); } // Last resort: parse localStorage directly try { const authItem = localStorage.getItem('sb-bkshbzaxaoyizhpgjhke-auth-token'); if (authItem) { const authData = JSON.parse(authItem); if (authData?.user?.id) { console.log('Got user from localStorage'); cachedUserId.current = authData.user.id; return authData.user.id; } } } catch (error) { console.log(' localStorage parse failed:', error); } console.log('No user found'); cachedUserId.current = null; return null; };
1 Reply
inder
inder2mo ago
looks like the Important note in the linked docs might apply here https://supabase.com/docs/reference/javascript/auth-onauthstatechange
JavaScript: Listen to auth events | Supabase Docs
Supabase API reference for JavaScript: Listen to auth events

Did you find this page helpful?