当我在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
}
}
}
1条答案
按热度按时间ncgqoxb01#
您应该使用
getServerSession
,因为您在getServerSideProps
中。getSession()
只能在客户端使用,正如他们在文档中所说:NextAuth.js提供了一个
getSession()
helper,它应该被调用仅在客户端以返回当前活动的会话。下面是一个如何使用
getServerSession
的示例: