Add detailed logging to diagnose session persistence

cgen-57a779f645c946618b4c383c0aef73f9
This commit is contained in:
Builder.io 2025-11-05 02:53:01 +00:00
parent 38f1a99326
commit 14a027fbb1

View file

@ -197,25 +197,37 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
const hasAuthTokens = () => { const hasAuthTokens = () => {
if (typeof window === "undefined") return false; if (typeof window === "undefined") return false;
const keys = Object.keys(window.localStorage); const keys = Object.keys(window.localStorage);
return keys.some( const authKeys = keys.filter(
(key) => (key) =>
key.includes("auth-token") || key.includes("auth-token") ||
(key.includes("sb-") && key.includes("-auth")), (key.includes("sb-") && key.includes("-auth")),
); );
console.log("[AUTH] Auth keys in localStorage:", authKeys);
return authKeys.length > 0;
}; };
// Get initial session with persistence recovery // Get initial session with persistence recovery
const initializeAuth = async () => { const initializeAuth = async () => {
try { try {
console.log("[AUTH] Initializing auth context...");
const { const {
data: { session }, data: { session },
} = await supabase.auth.getSession(); } = await supabase.auth.getSession();
console.log(
"[AUTH] getSession() returned:",
session?.user ? `User: ${session.user.email}` : "No session",
);
// Check localStorage directly
const hasTokens = hasAuthTokens();
console.log("[AUTH] Tokens exist in storage:", hasTokens);
// If no session but tokens exist, the session might not have restored yet // If no session but tokens exist, the session might not have restored yet
// Wait a bit for onAuthStateChange to trigger // Wait a bit for onAuthStateChange to trigger
if (!session && hasAuthTokens()) { if (!session && hasTokens) {
console.log( console.log(
"Tokens exist in storage but session not yet restored, waiting...", "[AUTH] Tokens exist in storage but session not yet restored, waiting for onAuthStateChange...",
); );
// Don't set loading to false yet - wait for onAuthStateChange // Don't set loading to false yet - wait for onAuthStateChange
return; return;
@ -223,15 +235,17 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
if (session?.user) { if (session?.user) {
sessionRestored = true; sessionRestored = true;
console.log("[AUTH] Session restored from getSession()");
setSession(session); setSession(session);
setUser(session.user); setUser(session.user);
await fetchUserProfile(session.user.id); await fetchUserProfile(session.user.id);
} else { } else {
console.log("[AUTH] No session found, marking as initialized");
sessionRestored = true; sessionRestored = true;
setLoading(false); setLoading(false);
} }
} catch (error) { } catch (error) {
console.error("Error getting session:", error); console.error("[AUTH] Error getting session:", error);
sessionRestored = true; sessionRestored = true;
setLoading(false); setLoading(false);
} }