NeahFront9/components/auth/auth-check.tsx

33 lines
1.0 KiB
TypeScript

"use client";
import { useSession } from "next-auth/react";
import { usePathname, useRouter } from "next/navigation";
import { useEffect } from "react";
export function AuthCheck({ children }: { children: React.ReactNode }) {
const { data: session, status } = useSession();
const pathname = usePathname();
const router = useRouter();
useEffect(() => {
// Only redirect if we're certain the user is not authenticated
// and we're not already on the signin page
if (status === "unauthenticated" && pathname !== "/signin") {
router.replace("/signin");
}
}, [status, pathname, router]);
// During loading, show the children to prevent flashing
// This works because server-side session check will handle protection
if (status === "loading") {
return <>{children}</>;
}
// If we're on the signin page, or if we're authenticated, show the children
if (pathname === "/signin" || status === "authenticated") {
return <>{children}</>;
}
// Otherwise, render nothing while redirecting
return null;
}