(options?: UseSessionOptions<R>)
| 85 | * [Documentation](https://next-auth.js.org/getting-started/client#usesession) |
| 86 | */ |
| 87 | export function useSession<R extends boolean>(options?: UseSessionOptions<R>) { |
| 88 | // @ts-expect-error Satisfy TS if branch on line below |
| 89 | const value: SessionContextValue<R> = React.useContext(SessionContext) |
| 90 | if (!value && process.env.NODE_ENV !== "production") { |
| 91 | throw new Error( |
| 92 | "[next-auth]: `useSession` must be wrapped in a <SessionProvider />" |
| 93 | ) |
| 94 | } |
| 95 | |
| 96 | const { required, onUnauthenticated } = options ?? {} |
| 97 | |
| 98 | const requiredAndNotLoading = required && value.status === "unauthenticated" |
| 99 | |
| 100 | React.useEffect(() => { |
| 101 | if (requiredAndNotLoading) { |
| 102 | const url = `/api/auth/signin?${new URLSearchParams({ |
| 103 | error: "SessionRequired", |
| 104 | callbackUrl: window.location.href, |
| 105 | })}` |
| 106 | if (onUnauthenticated) onUnauthenticated() |
| 107 | else window.location.href = url |
| 108 | } |
| 109 | }, [requiredAndNotLoading, onUnauthenticated]) |
| 110 | |
| 111 | if (requiredAndNotLoading) { |
| 112 | return { data: value.data, status: "loading" } as const |
| 113 | } |
| 114 | |
| 115 | return value |
| 116 | } |
| 117 | |
| 118 | export type GetSessionParams = CtxOrReq & { |
| 119 | event?: "storage" | "timer" | "hidden" | string |
no outgoing calls
searching dependent graphs…