I’m trying to implement Facebook login and session by using nextauth in a next.js project.
once the user is authenticated I want to retrieve the session and pass it to my component as a server-side prop to avoid unnecessary load time
My […nextauth.js] file
import NextAuth from "next-auth"
import FacebookProvider from "next-auth/providers/facebook";
export default NextAuth({
// Configure one or more authentication providers
secret: process.env.SECRET,
providers: [
FacebookProvider({
clientId: process.env.FACEBOOK_CLIENT_ID,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
}),
// ...add more providers here
],
})
I’ve double-checked my env variables FACEBOOK_CLIENT_ID FACEBOOK_CLIENT_SECRET NEXTAUTH_URL and SECRET
my _app.js file
import "../styles/globals.css";
import { SessionProvider } from "next-auth/react"
export default function App({
Component,
pageProps: { session, ...pageProps }
}) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
)
}
In my index.js component, I’m handling the login
import { useSession, signIn, signOut,getSession } from "next-auth/react"
import Head from 'next/head'
import Header from '../components/Header'
import Login from '../components/Login'
export default function Home({session}) {
if (!session) return <Login></Login>
return (
<div >
<Head>
<title>Facebook</title>
</Head>
<h1>Signed in as {session.user.email}</h1>
<Header/>
<main>
{/* Sidebar */}
{/* feed */}
{/* widgets */}
</main>
</div>
)
}
export async function getServerSideProps(context) {
const session = await getSession(context)
return {
props: { session }
}
}
In mi Login.js component I’m just using the signIn method provided by next auth
The thing is:
- When I try to retrieve the session by using getServerSideProps it doesn’t provide me a session and I cannot get to the home page, BUT if I instead use the custom hook inside the component, I get a session and everything works fine, but I think it is better if I pass the session as a serverside prop
const session = await getSession() //this works but is client-side
-
Is there something I’m missing out on? I’ve read the docs and followed the steps but it doesn’t quite work
-
besides Is there a difference between next-auth/react and next-auth/client?
I have “next-auth”: “^4.0.0-beta.7” package installed in this proyect
If anyone could shed some light over this topic and on why I cant get the session as a serverSide prop I would be thankful.