Neah/components/auth/auth-check.tsx
2025-05-03 13:32:50 +02:00

51 lines
1.6 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 }) {
// Wrap in try-catch to ensure it never crashes
try {
const session = useSession();
const pathname = usePathname();
const router = useRouter();
// Safely extract status with a fallback
const status = session?.status || "loading";
useEffect(() => {
try {
// Only redirect if we're certain the user is unauthenticated
if (status === "unauthenticated" && pathname && !pathname.includes("/signin")) {
if (router && typeof router.push === 'function') {
router.push("/signin");
}
}
} catch (error) {
console.error("Error in AuthCheck useEffect:", error);
}
}, [status, router, pathname]);
// Simple loading state
if (status === "loading") {
return (
<div className="flex justify-center items-center min-h-screen">
<div className="animate-spin h-10 w-10 border-4 border-blue-500 rounded-full border-t-transparent"></div>
</div>
);
}
// Don't render on unauthenticated
if (status === "unauthenticated" && pathname && !pathname.includes("/signin")) {
return null;
}
// Render children if authenticated
return <>{children}</>;
} catch (error) {
// If anything fails, just render the children
console.error("Error in AuthCheck component:", error);
return <>{children}</>;
}
}