Files
ColaFlow-Web/components/providers/AuthGuard.tsx
Yaojia Wang d9228057bb fix(frontend): Fix auth hydration and auto-redirect to login
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 <noreply@anthropic.com>
2025-11-05 21:12:15 +01:00

37 lines
1.1 KiB
TypeScript

'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/stores/authStore';
import { useCurrentUser } from '@/lib/hooks/useAuth';
export function AuthGuard({ children }: { children: React.ReactNode }) {
const router = useRouter();
const { isAuthenticated, isHydrated } = useAuthStore();
const { isLoading: isUserLoading } = useCurrentUser();
useEffect(() => {
if (isHydrated && !isUserLoading && !isAuthenticated) {
console.log('[AuthGuard] Redirecting to login - user not authenticated');
router.push('/login');
}
}, [isAuthenticated, isHydrated, isUserLoading, router]);
if (!isHydrated || isUserLoading) {
return (
<div className="flex min-h-screen items-center justify-center">
<div className="text-center">
<div className="mx-auto h-12 w-12 animate-spin rounded-full border-b-2 border-blue-600"></div>
<p className="mt-4 text-gray-600">Loading...</p>
</div>
</div>
);
}
if (!isAuthenticated) {
return null;
}
return <>{children}</>;
}