Spaces:
Sleeping
Sleeping
File size: 1,386 Bytes
d084ead | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | '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>;
}
|