3v324v23's picture
Merge Conflict solved | Build error solved
205f25f
Raw History Blame Contribute Delete
1.39 kB
'use client';
import { useEffect, useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { useAuthStore } from '@/store/authStore';
import { AppLayout } from './AppLayout';
const PUBLIC_ROUTES = ['/login'];
export function ClientLayout({ children }: { children: React.ReactNode }) {
const { isAuthenticated, loadFromStorage } = useAuthStore();
const pathname = usePathname();
const router = useRouter();
const [hydrated, setHydrated] = useState(false);
useEffect(() => {
loadFromStorage(); // read token + user from localStorage on first render
setHydrated(true);
}, [loadFromStorage]);
const isPublicRoute = PUBLIC_ROUTES.includes(pathname);
useEffect(() => {
if (hydrated && !isAuthenticated && !isPublicRoute) {
router.replace('/login');
}
}, [hydrated, isAuthenticated, isPublicRoute, router]);
// Don't render anything until localStorage has been read.
// Prevents flash of protected content before redirect fires.
if (!hydrated) return null;
// Public routes (login page) render with no layout wrapper
if (isPublicRoute) return <>{children}</>;
// Not yet authenticated — redirect is in-flight, show nothing
if (!isAuthenticated) return null;
// Authenticated — render the full app shell
return <AppLayout>{children}</AppLayout>;
}