Matthew C.
—When using NextAuth in a Next.js 13+ application that uses the recommended app router, you may encounter the following error:
Error: [next-auth]: `useSession` must be wrapped in a <SessionProvider />
You may also encounter this related error:
Error: React Context is unavailable in Server Components
Make sure that your Next.js layout, which is a UI shared between multiple routes, is wrapped with SessionProvider
. For example, in your src/app/layout.tsx
file:
export default async function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { const session = await getServerSession(); return ( <html lang="en"> <body className={inter.className}> <SessionProviderClientComponent session={session}> <main> <NavMenu /> {children} </main> </SessionProviderClientComponent> </body> </html> ); }
The 'useSession' must be wrapped in a <SessionProvider />
error occurs if you try to use the useSession
hook to access session
information where the NextAuth session
object is not available. The SessionProvider
uses React Context to share the session
object between components, which can be accessed using the useSession
hook.
The React Context is unavailable in Server Components
error occurs when you try to use the SessionProvider
component in a server component.
The getServerSession
method is used to get the session
object as the RootLayout
component is a server component that’s rendered on the server.
The SessionProviderClientComponent
is the SessionProvider
returned from a client component:
"use client"; import { Session } from "next-auth"; import { SessionProvider } from "next-auth/react"; export default function SessionProviderClientComponent({ children, session, }: { children: React.ReactNode; session: Session | null; }) { return <SessionProvider session={session}>{children}</SessionProvider>; }
The SessionProvider
needs to be used in a client component as it uses React Context. The "use client"
directive is added to the top of the file to make the component a client component.
If you are using the App Router, try to avoid using the SessionProvider
and use getServerSession
instead to get access to the session
object as using SessionProvider
should be unnecessary in most cases. However, using the SessionProvider
can be useful if you are migrating from the older pages router.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.