Nextauth authentication not working with nextjs app?

544 Views Asked by At

So I was watching this youtube tutorial and at around 1:12:00, my app stops working. After some research, I found out that Provider is deprecated in v4 and needed to use SessionProvider. So the code in '_app.js' file looks like this.

import { SessionProvider } from 'next-auth/react';
import { Session } from "next-auth"

function MyApp({ Component, pageProps }) {
return (
   <SessionProvider session={pageProps.session}>
     {/* <Provider store={store}> */}
       <Component {...pageProps} />
     {/* </Provider> */}
   </SessionProvider>
 )
}

export default MyApp

The code in [...nextauth].js looks like this.

import NextAuth from 'next-auth'
import { SessionProvider } from 'next-auth/react';


export default NextAuth ({
// Configure one or more authentication providers
SessionProvider: [
    Providers.Facebook({
        clientId: process.env.FACEBOOK_CLIENT_ID,
        clientSecret: process.env.FACEBOOK_CLIENT_SECRET
    })
    // ... add more providers here
 ]
})

The code in index.js looks like this.

import Head from 'next/head'
import Header from '../components/Header'
import Login from '../components/Login';

import { useSession } from "next-auth/react"

// import { SessionProvider } from "next-auth/react"
// import { Session } from "next-auth"


export default function Home( { session }) {
  if(!session) return <Login /> ;

return (
    <div>
      <Head>
        <title>Facebook</title>
      </Head>

      {/* Header */}
      <Header />

      <main>
        {/* Sidebar */}
        {/* Feed */}
        {/* Widgets */}
      </main>
    </div>
  )
}

export async function getServerSideProps(context) {
  // Get the user
  const { data: session } = useSession();

  return {
    prop:{
      session
    }
  }
}

I tried reading the documentation and watched some videos as well but different videos are using different technique. I would like to understand Next Auth and I would appreciate it if someone could explain them to me or point me in the right direction. I have been looking for new videos on youtube as well since the video I am watching is outdated. Thank you.

1

There are 1 best solutions below

1
Yilmaz On
const { data: session } = useSession();

useSession is a hook and hooks are react.js specific. useSession works only in client components, it does not work on the server. Use this on the server

import { getSession } from "next-auth/react";

export async function getServerSideProps(context) {
  const session = await getSession({ req: context.req });
   
  return {
    // you typed `prop`
    props: {session},
  };
}