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

Next.js中getServerSideProps序列化Cookie报错及登出清Cookie问题

问题解决:Next.js Cookie登录序列化错误及登出清除方法

1. 修复getServerSideProps序列化错误

报错原因是:当用户未登录时,context.req.headers.cookie的值为undefined,而Next.js要求getServerSideProps返回的props必须是可序列化的JSON,undefined无法被JSON序列化,因此触发错误。

提供两种修复方案:

方案一:将undefined转为null

export async function getServerSideProps(context: { req: { headers: { cookie: any; }; }; }) {
    
  const cookies = context.req.headers.cookie;
  if (cookies) {
    return {
      redirect: {
        permanent: false,
        destination: "/dashboard",
      },
      props:{},
    };
  }
  
  return {
    props: {
      cookies: cookies || null, // 把undefined转为可序列化的null
    },
  };
}

方案二:不返回不存在的cookies字段

export async function getServerSideProps(context: { req: { headers: { cookie: any; }; }; }) {
    
  const cookies = context.req.headers.cookie;
  if (cookies) {
    return {
      redirect: {
        permanent: false,
        destination: "/dashboard",
      },
      props:{},
    };
  }
  
  return {
    props: {}, // 不包含cookies字段,避免传递undefined
  };
}

2. 登出时清除Cookie

直接使用你当前使用的Cookies库的remove方法即可:

Cookies.remove('email')

注意:如果设置Cookie时指定了path或domain参数,清除时必须传入相同参数才能成功清除。比如设置Cookie时的代码是:

Cookies.set('email', email, { path: '/', domain: 'yourdomain.com' })

则清除时需要对应:

Cookies.remove('email', { path: '/', domain: 'yourdomain.com' })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:40:44