MCPcopy
hub / github.com/nextauthjs/next-auth / useSession

Function useSession

src/react/index.tsx:87–116  ·  view source on GitHub ↗
(options?: UseSessionOptions<R>)

Source from the content-addressed store, hash-verified

85 * [Documentation](https://next-auth.js.org/getting-started/client#usesession)
86 */
87export 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
118export type GetSessionParams = CtxOrReq & {
119 event?: "storage" | "timer" | "hidden" | string

Callers 8

AppFunction · 0.90
SessionConsumerFunction · 0.90
HeaderFunction · 0.90
PageFunction · 0.90
credentials.jsFile · 0.90
email.jsFile · 0.90
PageFunction · 0.85

Calls

no outgoing calls

Tested by 2

AppFunction · 0.72
SessionConsumerFunction · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…