Next.js Discord

Discord Forum

Qeustion About useSession();

Unanswered
Atlantic mackerel posted this in #help-forum
Open in Discord
Atlantic mackerelOP
Hey guys, Im trying to add LoginProvider,
So I tried this:

signin-button.tsx file

"use client"
import {SessionProvider, useSession} from "next-auth/react";
import Image from "next/image";
import GoogleLightButton from "@/public/google/web_dark_sq_SI.svg";

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

    return (
        <SessionProvider>
            <div className="hover:cursor-pointer" onClick={(event) => {
                console.log("test")
            }}>
                <Image
                    priority
                    src={GoogleLightButton}
                    alt="Follow us on Twitter"
                />
            </div>
        </SessionProvider>

    )
}

export default SigninButton


But the error said:

Error: React Context is unavailable in Server Components


login-page.tsx

import SigninButton from "@/components/provider/signin-button";
import {SessionProvider} from "next-auth/react";

export default function Page() {
    return (

        <div className="flex w-screen justify-center">
                <SigninButton/>
        </div>
    )
}


how can I fix it? andd can you gimme some advice to add AuthProvider?

8 Replies

Morelet’s Crocodile
If you want to use a context in a component , you'll have to change it to client component.
write "use client" at the top of component
French Lop
I would suggest looking at the docs of NextAuth again, you have to wrap your app into the SessionProvider, or at least all components you are trying to use useSession in.
Here is an example you can look at https://github.com/nextauthjs/next-auth-example
@Morelet’s Crocodile If you want to use a context in a component , you'll have to change it to client component. write "use client" at the top of component
Atlantic mackerelOP
As You can see it on SignIn button has already "use client" this should be on Page() file too?
Orinoco Crocodile
What does one do if using the modern App Router? The documentation references adding the _app.tsx:
import { SessionProvider } from "next-auth/react"
import type { AppProps } from "next/app"

export default function App({
  Component,
  pageProps: { session, ...pageProps },
}: AppProps) {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  )
}


But it doesn't seem that abstraction is correct for App Router.
This documentation points out SessionProvider can't be put in the Root layout - but I'm not really sure where else to put it. All of my pages require being logged in. https://next-auth.js.org/getting-started/example#configure-shared-session-state
French Lop
You may want to look at their experimental docs for this https://authjs.dev/reference/nextjs
And check out an App Router example, this should answer most of your questions.