Nextauth身份验证无法与nextjs应用程序一起使用?

hec6srdp  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(121)

所以我正在看这个youtube tutorial,大约在1:12:00,我的应用程序停止工作。经过一些研究,我发现Provider在v4中被弃用,需要使用SessionProvider。所以'_app.js'文件中的代码看起来像这样。

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

[...nextauth].js中的代码看起来像这样。

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
 ]
})

index.js中的代码看起来像这样。

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
    }
  }
}

我试着阅读文档,也看了一些视频,但不同的视频使用不同的技术。我想了解Next Auth,如果有人能向我解释或指出正确的方向,我将不胜感激。我一直在寻找新的视频在youtube以及由于视频我正在看的是过时的。谢谢大家。

xxe27gdn

xxe27gdn1#

const { data: session } = useSession();

useSession是一个钩子,钩子是react.js特有的。useSession只能在客户端组件中工作,不能在服务器上工作。在服务器上使用这个

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

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

相关问题