next.js getSession返回的会话在getServerSideProps中可见,但在组件中未定义

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

当我在Dashboard中控制台记录session时,它返回undefined,而在getServerSideProps中控制台记录正在工作,它显示了详细信息。我做错什么了吗?
目标:我试图获取serverSideProps上的会话信息(同时使其成为一个受保护的路由,以使未经身份验证的用户返回主页),一旦我完成了获取会话信息,我想控制台记录它(这样我就可以继续我的代码并将其传递给组件)。
dashboard.tsx

import Details from '@/sections/Dashboard/Details';
import LatestCampaigns from '@/sections/Dashboard/LatestCampaigns';
import Footer from '@/sections/Footer';
import Navbar from '@/sections/Navbar'
import { GetServerSideProps } from 'next';
import { Session } from 'next-auth';
import { getSession } from 'next-auth/react';
import React from 'react';

export interface Props {
  session: Session | null
}

const Dashboard = ({ session }: Props) => {
  console.log(`Dashboard: ${session}`);
  console.info(session);

  return (
    <>
      <Navbar />
      <Details />
      <main>
        <LatestCampaigns />
        <Footer />
      </main>
    </>
  )
}

export default Dashboard;

export const getServerSideProps: GetServerSideProps<Props> = async (context) => {
  const _sess = await getSession(context);

  console.log('Checking..');
  console.info(_sess);

  if (!_sess) {
    return {
      redirect: {
        destination: '/',
        permanent: false
      },
      props: {}
    }
  }

  return {
    props: {
      session: _sess
    }
  }
}

我也试过直接传递它而不是使用变量

export const getServerSideProps: GetServerSideProps<Props> = async (context) => {
  const session = await getSession(context);

  console.log('Checking..');
  console.info(session );

  if (!session ) {
    return {
      redirect: {
        destination: '/',
        permanent: false
      },
      props: {}
    }
  }

  return {
    props: {
      session
    }
  }
}
ncgqoxb0

ncgqoxb01#

您应该使用getServerSession,因为您在getServerSideProps中。getSession()只能在客户端使用,正如他们在文档中所说:
NextAuth.js提供了一个getSession() helper,它应该被调用仅在客户端以返回当前活动的会话。
下面是一个如何使用getServerSession的示例:

// [...nextauth].ts

import NextAuth from 'next-auth'
import type { NextAuthOptions } from 'next-auth'

export const authOptions: NextAuthOptions = {
  // your configs
}

export default NextAuth(authOptions);
import { authOptions } from 'pages/api/auth/[...nextauth]'
import { getServerSession } from "next-auth/next"

export const getServerSideProps: GetServerSideProps<Props> = async (context) => {
  const session = await getServerSession(context.req, context.res, authOptions);

  console.log(session);

  if (!session ) {
    return {
      redirect: {
        destination: '/',
        permanent: false
      },
      props: {}
    }
  }

  return {
    props: {
      session
    }
  }
}

相关问题