在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
getServerSidePropsin "/account".
Reason: Props must be returned as a plain object from getServerSideProps:{ props: { ... } }.
问题分析
- 返回格式不符合要求:else分支直接返回
{},但Next.js要求getServerSideProps必须返回包含props/redirect/notFound的结构化对象,哪怕是空props也要写成{ props: {} }。 - 变量作用域错误:
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
相关产品推荐
相关产品推荐

