freshyo/apps/web-ui/src/components/ProtectedRoute.tsx
2026-10-06 11:53:12 +05:30

31 lines
1 KiB
TypeScript

import React, { useEffect } from 'react'
import { useAuth } from '../lib/auth-context'
import { useNavigate, useLocation } from '@tanstack/react-router'
export function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { isAuthenticated, isLoading } = useAuth()
const navigate = useNavigate()
const location = useLocation()
useEffect(() => {
if (isLoading) return
if (isAuthenticated) return
// Preserve full target (path + query) with a timestamp, like native AUTH_REDIRECT_KEY
const target = location.pathname + location.search
sessionStorage.setItem('auth_redirect', JSON.stringify({ target, at: Date.now() }))
navigate({ to: '/login', search: { redirect: target } })
}, [isAuthenticated, isLoading])
if (isLoading) {
return (
<div className="flex min-h-screen items-center justify-center">
<div className="h-8 w-8 animate-spin rounded-full border-4 border-brand-500 border-t-transparent" />
</div>
)
}
if (!isAuthenticated) return null
return <>{children}</>
}