{"record":{"id":"51d61cf38653d0b9","repo":"nextauthjs/next-auth","slug":"next-auth-usesession-must-be-wrapped-in-a-se","errorCode":null,"errorMessage":"[next-auth]: `useSession` must be wrapped in a <SessionProvider />","messagePattern":"\\[next-auth\\]: `useSession` must be wrapped in a <SessionProvider />","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/next-auth/src/react.tsx","lineNumber":144,"sourceCode":"\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\",\n        callbackUrl: window.location.href,\n      })}`\n      if (onUnauthenticated) onUnauthenticated()\n      else window.location.href = url\n    }\n  }, [requiredAndNotLoading, onUnauthenticated])","sourceCodeStart":126,"sourceCodeEnd":162,"githubUrl":"https://github.com/nextauthjs/next-auth/blob/a1a16a5a7780488c7449feece410033f445d0b31/packages/next-auth/src/react.tsx#L126-L162","documentation":"useSession must run inside a <SessionProvider> because it reads session state from React Context. When the context value is undefined (no provider above the component) and NODE_ENV is not production, next-auth throws this error to fail fast and explain the missing wrapper.","triggerScenarios":"Calling useSession in a client component whose tree does not include <SessionProvider> (typically in the root layout or a parent client component).","commonSituations":"Adding useSession in a new page/component without setting up SessionProvider in app/layout.tsx; provider present only in some routes while the hook is used elsewhere; migration where the provider was in _app.tsx (pages router) and never added to the app router layout.","solutions":["Wrap your app (or the subtree using useSession) in <SessionProvider> from \"next-auth/react\", e.g. in app/layout.tsx","Ensure the component calling useSession is a client component under that provider","Pass session data from the server via `<SessionProvider session={await auth()}>` in the root layout"],"exampleFix":"// before\n// app/layout.tsx\nexport default function RootLayout({ children }) {\n  return <html><body>{children}</body></html>\n}\n// after\nimport { SessionProvider } from \"next-auth/react\"\nexport default async function RootLayout({ children }) {\n  const session = await auth()\n  return (\n    <html><body>\n      <SessionProvider session={session}>{children}</SessionProvider>\n    </body></html>\n  )\n}","handlingStrategy":"validation","validationCode":"// In React 18+, detect a missing provider before calling the hook:\nfunction hasSessionProvider(): boolean {\n  // simplest check: wrap useSession consumers and verify via Context\n  return React.useContext(SessionContext) !== undefined // within a custom hook\n}\n// Or guard in dev:\nif (!document.querySelector('[data-session-provider]')) {\n  console.warn(\"SessionProvider is missing\")\n}","typeGuard":"function hasSession(\n  v: SessionContextValue<boolean> | null | undefined\n): v is SessionContextValue<boolean> {\n  return v != null\n}","tryCatchPattern":"let ctx\ntry {\n  ctx = useSession()\n} catch (e) {\n  if (e.message.includes(\"SessionProvider\")) {\n    // render a fallback / redirect to sign-in instead of crashing\n  } else throw e\n}","preventionTips":["Always mount <SessionProvider> in the root layout (app router) or _app.tsx (pages router)","Wrap useSession usage in a custom hook that checks the context first","Add a smoke test that renders a page using useSession to catch a missing provider","Pass the server-fetched session into <SessionProvider session={...}> for consistency"],"tags":["react","session","context","provider","nextjs"],"backgroundTag":"missing-context-provider","analyzedSha":"a1a16a5a7780488c7449feece410033f445d0b31","analyzedAt":"2026-08-28T21:52:38.200Z","schemaVersion":2},"datasetVersion":"2026-08-29T02:17:18.158Z"}