import { useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';
interface ProtectedRouteProps {
children: React.ReactNode;
}
export function ProtectedRoute({ children }: ProtectedRouteProps) {
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
// Check authentication status (API key is in HTTP-only cookie)
fetch('/auth/status', {
credentials: 'include' // Send cookies
})
.then(res => {
if (res.ok) {
return res.json();
}
throw new Error('Not authenticated');
})
.then(data => {
setIsAuthenticated(data.authenticated === true);
setIsLoading(false);
})
.catch(() => {
setIsAuthenticated(false);
setIsLoading(false);
});
}, []);
if (isLoading) {
// Show loading spinner while checking auth
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900">
<div className="text-white text-xl">Loading...</div>
</div>
);
}
if (!isAuthenticated) {
// Redirect to login if not authenticated
return <Navigate to="/login" replace />;
}
// Render protected content
return <>{children}</>;
}