Next.js中getServerSideProps序列化Cookie报错及登出清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
相关产品推荐
相关产品推荐

