( options?: UseSessionOptions<R> )
| 112 | * [Documentation](https://next-auth.js.org/getting-started/client#usesession) |
| 113 | */ |
| 114 | export function useSession<R extends boolean>( |
| 115 | options?: UseSessionOptions<R> |
| 116 | ): SessionContextValue<R> { |
| 117 | if (!SessionContext) { |
| 118 | throw new Error("React Context is unavailable in Server Components") |
| 119 | } |
| 120 | |
| 121 | // @ts-expect-error Satisfy TS if branch on line below |
| 122 | const value: SessionContextValue<R> = React.useContext(SessionContext) |
| 123 | if (!value && process.env.NODE_ENV !== "production") { |
| 124 | throw new Error( |
| 125 | "[next-auth]: `useSession` must be wrapped in a <SessionProvider />" |
| 126 | ) |
| 127 | } |
| 128 | |
| 129 | const { required, onUnauthenticated } = options ?? {} |
| 130 | |
| 131 | const requiredAndNotLoading = required && value.status === "unauthenticated" |
| 132 | |
| 133 | React.useEffect(() => { |
| 134 | if (requiredAndNotLoading) { |
| 135 | const url = `/api/auth/signin?${new URLSearchParams({ |
| 136 | error: "SessionRequired", |
| 137 | callbackUrl: window.location.href, |
| 138 | })}` |
| 139 | if (onUnauthenticated) onUnauthenticated() |
| 140 | else window.location.href = url |
| 141 | } |
| 142 | }, [requiredAndNotLoading, onUnauthenticated]) |
| 143 | |
| 144 | if (requiredAndNotLoading) { |
| 145 | return { |
| 146 | data: value.data, |
| 147 | update: value.update, |
| 148 | status: "loading", |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | return value |
| 153 | } |
| 154 | |
| 155 | export type GetSessionParams = CtxOrReq & { |
| 156 | event?: "storage" | "timer" | "hidden" | string |
no outgoing calls