Next.js Discord

Discord Forum

How to properly use `SessionProvider` in Next.js v14?

Answered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Northeast Congo LionOP
I'm trying to wrap my next.js project with the SessionProvider from next-auth, as the image below.
I didn't want to turn my RootLayout.tsx component to be a client-side, since I need to configure the Metadata.
But couldn't find a proper place to wrap with SessionProvider.

However, if I wrap them as in the image, the error happens.
What am I doing wrong?
Answered by B33fb0n3
you can create a component like GlobalProvider or something called like that. This component will be a clientside component. Inside that, you import your SessionProvider.

You can see your error described here (with the solution I mentioned): https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#using-context-providers

Also you can see, that if you pass it as children, that the children itself can stay server components: https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#supported-pattern-passing-server-components-to-client-components-as-props
View full answer

5 Replies

Answer
Northeast Congo LionOP
Thank you! But the error still exsists...
Oh, when I commented out that parts, it doesn't show the error.
But why..?
Conditional rendering is not allowed in this situation?
Oh, that's because the session.user could be null, so I have to null-check it.
Solved!

"use client";
import { useSession, signIn, signOut } from "next-auth/react";

const AuthButton = () => {
  const { data: session } = useSession();

  if (session) {
    return (
      <>
        Signed in as {session.user?.name}
        <button className="" onClick={() => signOut()}>
          Sign out
        </button>
      </>
    );
  }

  return (
    <>
      Not signed in
      <button className="" onClick={() => signIn()}>
        Sign in
      </button>
    </>
  );
};

export default AuthButton;
@Northeast Congo Lion Thank you! But the error still exsists...
remove this: