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

Function useSession

packages/next-auth/src/react/index.tsx:114–153  ·  view source on GitHub ↗
(
  options?: UseSessionOptions<R>
)

Source from the content-addressed store, hash-verified

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

Callers 13

AppFunction · 0.90
SessionConsumerFunction · 0.90
HeaderFunction · 0.90
ProtectedPageFunction · 0.90
MePageFunction · 0.90
layout.jsFile · 0.90
HomeFunction · 0.90
HeaderFunction · 0.90
PageFunction · 0.90
credentials.jsFile · 0.90
email.jsFile · 0.90

Calls

no outgoing calls

Tested by 2

AppFunction · 0.72
SessionConsumerFunction · 0.72