我正在嘗試通過在 next.js 專案中使用 nextauth 來實作 Facebook 登錄和會話。一旦用戶通過身份驗證,我想檢索會話并將其作為服務器端道具傳遞給我的組件,以避免不必要的加載時間
我的[...nextauth.js]檔案
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
],
})
我已經仔細檢查了我的環境變數 FACEBOOK_CLIENT_ID FACEBOOK_CLIENT_SECRET NEXTAUTH_URL 和 SECRET
我的_app.js檔案
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>
)
}
在我的index.js組件中,我正在處理登錄
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 }
}
}
在 mi Login.js組件中,我只是使用 next auth 提供的 signIn 方法
事情是:
- 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.
uj5u.com熱心網友回復:
我想我明白了,只是改變了 SessionProvider 在 _app.js 上獲取會話的方式
import { SessionProvider } from "next-auth/react"
export default function App({
Component,
pageProps,
}) {
return (
<SessionProvider session={pageProps.session}>
<Component {...pageProps} />
</SessionProvider>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/403472.html
標籤:
