Next.js Discord

Discord Forum

I am getting Error: [next-auth]: `useSession` must be wrapped in a <SessionProvider />. with next 13

Answered
Brown bear posted this in #help-forum
Open in Discord
Avatar
Brown bearOP
This is my layout.js where I am wrapping everything with the auth or trying to do so like this :

"use client";

import Navbar from "./components/Navbar";
import { UserProvider } from "./context/UserContext";
import "./globals.css";
import { SessionProvider } from "next-auth/react";
import { Session } from "next-auth";
import { useSession } from "next-auth/react";

export const metadata = {
  title: "",
  description: "",
};

export default function RootLayout({ children }) {
  const session = useSession();
  return (
    <html lang="en">
      <body>
        <SessionProvider session={session}>
          <UserProvider>
            <Navbar />
            {children}
          </UserProvider>
        </SessionProvider>
      </body>
    </html>
  );
}


Not sure whats wrong here and how to solve it
Answered by Orinoco Crocodile
You shouldn’t use “use client” in the layout file. Move the SessionProvider to another file which is use client and import it into the layout wrapping it around where you currently have SessionProvider
View full answer

2 Replies

Avatar
fuma 💙 joulev
It's not how you use Next Auth in App Router.
useSession reads a context, which means it can only be used under the provider. (in a client component)

In server components, you should use getServerSession to get the session instead.
Also, never make a page or layout client component, it is an anti-pattern.

Learn more about [Get Server Session](https://next-auth.js.org/configuration/nextjs#in-app-router)
Avatar
Orinoco Crocodile
You shouldn’t use “use client” in the layout file. Move the SessionProvider to another file which is use client and import it into the layout wrapping it around where you currently have SessionProvider
Answer