-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathSessionCheck.tsx
More file actions
51 lines (39 loc) · 1.15 KB
/
SessionCheck.tsx
File metadata and controls
51 lines (39 loc) · 1.15 KB
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
43
44
45
46
47
48
49
50
51
'use client'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { useEffect } from 'react'
import { useSession } from 'next-auth/react'
const SessionCheck = ({
children,
}: {
children: React.ReactNode
}): JSX.Element | null => {
const { data: session, status } = useSession()
const router = useRouter()
const searchParams = useSearchParams()
const pathname = usePathname()
const redirectTo = searchParams.get('redirectTo') ?? '/dashboard'
const preventRedirectOnPaths = [
'/organizations/create-organization',
'/organizations/agent-config',
'/organizations/dashboard',
]
useEffect(() => {
if (status === 'loading') {
return
}
const isOnRestrictedPage = preventRedirectOnPaths.some((page) =>
pathname.startsWith(page),
)
if (session && redirectTo && !isOnRestrictedPage) {
router.push(redirectTo)
}
if (session === null) {
localStorage.removeItem('persist:root')
}
}, [session, status, redirectTo, router, pathname])
if (status === 'loading') {
return <div>Loading session...</div>
}
return <>{children}</>
}
export default SessionCheck