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

在getServerSideProps中加条件遇序列化错误,如何解决?

解决getServerSideProps条件判断中的序列化错误问题

原代码

export async function getServerSideProps(context) {
  const jwt = parseCookies(context).jwt || null;
  if (jwt) {
    const user = parseJwt(jwt);
    const userId = user.id;
    console.log(userId);
  } else {
    return {};
  }
  return {
    props: { jwt, userId },
  };
}

报错信息

Error: Error serializing props returned from getServerSideProps in "/account".
Reason: Props must be returned as a plain object from getServerSideProps: { props: { ... } }.

问题分析

  1. 返回格式不符合要求:else分支直接返回{},但Next.js要求getServerSideProps必须返回包含props/redirect/notFound的结构化对象,哪怕是空props也要写成{ props: {} }。
  2. 变量作用域错误:userId是在if块内部声明的,外部return语句无法访问该变量,会引发未定义错误。

修正方案

方案1:统一返回props结构

提升userId的作用域,确保所有分支都返回符合要求的结构:

export async function getServerSideProps(context) {
  const jwt = parseCookies(context).jwt || null;
  let userId = null; // 提前声明变量,扩大作用域

  if (jwt) {
    const user = parseJwt(jwt);
    userId = user.id;
    console.log(userId);
  }

  // 所有路径统一返回标准结构
  return {
    props: { jwt, userId },
  };
}

方案2:未登录时重定向(更符合业务逻辑)

如果未登录需要跳转到登录页,可使用redirect返回结构:

export async function getServerSideProps(context) {
  const jwt = parseCookies(context).jwt || null;

  // 未登录直接重定向,提前终止函数
  if (!jwt) {
    return {
      redirect: {
        destination: '/login',
        permanent: false,
      },
    };
  }

  // 已登录逻辑
  const user = parseJwt(jwt);
  const userId = user.id;
  console.log(userId);

  return {
    props: { jwt, userId },
  };
}

关键说明

  • 必须保证getServerSideProps的返回值是Next.js规定的结构:要么是{ props: ... },要么是{ redirect: ... }或{ notFound: true },不能返回空对象。
  • 变量作用域要覆盖到所有使用它的代码块,避免未定义错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:05:23