{"record":{"id":"3941e3adc6c65ad5","repo":"nextauthjs/next-auth","slug":"react-context-is-unavailable-in-server-components","errorCode":null,"errorMessage":"React Context is unavailable in Server Components","messagePattern":"React Context is unavailable in Server Components","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/next-auth/src/react.tsx","lineNumber":138,"sourceCode":"          status: \"unauthenticated\" | \"loading\"\n        }\n\nexport const SessionContext = React.createContext?.<\n  SessionContextValue | undefined\n>(undefined)\n\n/**\n * React Hook that gives you access to the logged in user's session data and lets you modify it.\n *\n * :::info\n * `useSession` is for client-side use only and when using [Next.js App Router (`app/`)](https://nextjs.org/blog/next-13-4#nextjs-app-router) you should prefer the `auth()` export.\n * :::\n */\nexport function useSession<R extends boolean>(\n  options?: UseSessionOptions<R>\n): SessionContextValue<R> {\n  if (!SessionContext) {\n    throw new Error(\"React Context is unavailable in Server Components\")\n  }\n\n  // @ts-expect-error Satisfy TS if branch on line below\n  const value: SessionContextValue<R> = React.useContext(SessionContext)\n  if (!value && process.env.NODE_ENV !== \"production\") {\n    throw new Error(\n      \"[next-auth]: `useSession` must be wrapped in a <SessionProvider />\"\n    )\n  }\n\n  const { required, onUnauthenticated } = options ?? {}\n\n  const requiredAndNotLoading = required && value.status === \"unauthenticated\"\n\n  React.useEffect(() => {\n    if (requiredAndNotLoading) {\n      const url = `${__NEXTAUTH.basePath}/signin?${new URLSearchParams({\n        error: \"SessionRequired\",","sourceCodeStart":120,"sourceCodeEnd":156,"githubUrl":"https://github.com/nextauthjs/next-auth/blob/a1a16a5a7780488c7449feece410033f445d0b31/packages/next-auth/src/react.tsx#L120-L156","documentation":"useSession relies on React Context, which is not supported in React Server Components. In next-auth v5, the react.tsx module guards this by throwing an Error when the SessionContext is undefined (i.e. the hook was called in an RSC environment). Session data must be fetched server-side with auth()/getSession instead.","triggerScenarios":"Calling the useSession hook inside a Server Component (app router component without \"use client\"), where React.useContext/Context is unavailable so SessionContext is undefined.","commonSituations":"Calling useSession in an app/ directory server component; forgetting the \"use client\" directive after migrating from pages router; building a shared component used in both server and client trees.","solutions":["Add \"use client\" at the top of the component calling useSession","In server components, fetch the session with `await auth()` (v5) or `await getServerSession(authOptions)` instead","Split the component: keep the server component for data, delegate session-dependent UI to a client child component"],"exampleFix":"// before\n// app/profile.tsx (no directive)\nimport { useSession } from \"next-auth/react\"\nconst { data } = useSession()\n// after\n// app/profile.tsx\nimport { auth } from \"next-auth\"\nexport default async function Profile() {\n  const session = await auth()\n}\n// or add \"use client\" to keep useSession","handlingStrategy":"type-guard","validationCode":"// In a server component, don't use the hook; fetch directly:\n// const session = await auth() // v5\n// Guard: only call the hook in client components\nfunction isClientComponent() {\n  return typeof window !== \"undefined\" && typeof React.useContext === \"function\"\n}","typeGuard":"function canUseSessionContext(): boolean {\n  // SessionContext is undefined in RSC builds of the module\n  return typeof window !== \"undefined\"\n}\nif (!canUseSessionContext()) {\n  // use server-side auth() instead\n}","tryCatchPattern":"let session\ntry {\n  session = useSession()\n} catch (e) {\n  if (e.message.includes(\"Server Components\")) {\n    // render login placeholder / redirect; fetch session server-side instead\n  } else throw e\n}","preventionTips":["Add \"use client\" to every file that calls next-auth hooks","In server components always use auth()/getServerSession, never useSession","Structure components so session UI lives in leaf client components","Enable lint rules that flag next-auth hooks in files without \"use client\""],"tags":["react","server-components","nextjs","hooks"],"backgroundTag":"react-context-in-server-component","analyzedSha":"a1a16a5a7780488c7449feece410033f445d0b31","analyzedAt":"2026-08-28T21:52:38.200Z","schemaVersion":2},"datasetVersion":"2026-08-29T02:17:18.158Z"}