You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

getServerSideProps中session正常,组件内却为undefined的问题排查

问题解决:Dashboard组件session为undefined,但getServerSideProps中正常

问题现象

在getServerSideProps内打印session能显示完整信息,但Dashboard组件内打印session返回undefined;需要实现路由保护(未认证用户重定向至首页)并将session传递给组件使用。

核心问题

你在服务器端的getServerSideProps中错误导入了客户端版本的getSession方法。从next-auth/react导入的getSession是为客户端环境设计的,在服务器端调用会导致session无法正确传递到组件。

修复步骤

  1. 修正getSession的导入路径
    将导入语句从:

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

    改为:

    import { getSession } from 'next-auth';
    
  2. 统一props结构符合接口定义
    未检测到session时,显式传递session: null以匹配Props接口:

    if (!session) {
      return {
        redirect: {
          destination: '/',
          permanent: false
        },
        props: { session: null }
      }
    }
    
  3. 完整修正后的代码

    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';
    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 session = await getSession(context);
    
      console.log('Checking..');
      console.info(session);
    
      if (!session) {
        return {
          redirect: {
            destination: '/',
            permanent: false
          },
          props: { session: null }
        }
      }
    
      return {
        props: {
          session
        }
      }
    }
    

额外优化提示

  • 组件内原console.log(Dashboard: ${session})会因字符串拼接将对象转为[object Object],改为console.log('Dashboard:', session)可查看完整session结构。
  • 确保你的NextAuth配置文件(如[...nextauth].ts)正确设置了session策略,服务器端获取session需要对应配置支持。

内容的提问来源于stack exchange,提问作者Ali Wayne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:25:27