From d9228057bbae70026389b546bb51f022b46c353a Mon Sep 17 00:00:00 2001 From: Yaojia Wang Date: Wed, 5 Nov 2025 21:12:15 +0100 Subject: [PATCH] fix(frontend): Fix auth hydration and auto-redirect to login MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix issue where unauthenticated users were not automatically redirected to the login page. Root Cause: - authStore.ts: isLoading was not set to false after hydration - AuthGuard.tsx: Used isLoading instead of isHydrated for checks Changes: - Set isLoading = false in authStore onRehydrateStorage callback - Changed AuthGuard to use isHydrated instead of isLoading - Added console log for redirect debugging This ensures: - Hydration completes with correct loading state - Unauthenticated users are immediately redirected to /login - More explicit state management with isHydrated 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- components/providers/AuthGuard.tsx | 9 +++++---- stores/authStore.ts | 4 +++- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/components/providers/AuthGuard.tsx b/components/providers/AuthGuard.tsx index 34d7fa9..61deabc 100644 --- a/components/providers/AuthGuard.tsx +++ b/components/providers/AuthGuard.tsx @@ -7,16 +7,17 @@ import { useCurrentUser } from '@/lib/hooks/useAuth'; export function AuthGuard({ children }: { children: React.ReactNode }) { const router = useRouter(); - const { isAuthenticated, isLoading } = useAuthStore(); + const { isAuthenticated, isHydrated } = useAuthStore(); const { isLoading: isUserLoading } = useCurrentUser(); useEffect(() => { - if (!isLoading && !isUserLoading && !isAuthenticated) { + if (isHydrated && !isUserLoading && !isAuthenticated) { + console.log('[AuthGuard] Redirecting to login - user not authenticated'); router.push('/login'); } - }, [isAuthenticated, isLoading, isUserLoading, router]); + }, [isAuthenticated, isHydrated, isUserLoading, router]); - if (isLoading || isUserLoading) { + if (!isHydrated || isUserLoading) { return (
diff --git a/stores/authStore.ts b/stores/authStore.ts index 056b599..edf27d8 100644 --- a/stores/authStore.ts +++ b/stores/authStore.ts @@ -57,9 +57,11 @@ export const useAuthStore = create()( } state.isHydrated = true; + state.isLoading = false; // 水合完成后停止 loading console.log('[AuthStore] Hydration completed', { userId: state.user?.id, - isAuthenticated: state.isAuthenticated + isAuthenticated: state.isAuthenticated, + isLoading: state.isLoading }); } },