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

Next.js中使用getServerSideProps获取cookie返回undefined如何解决?

问题修复方案

1. 修复变量重名冲突

你当前代码的getServerSideProps入参已经声明了res变量,后续调用fetch时又重新定义了同名的res变量,会导致上下文错乱,这是最可能的直接原因,先修改这个问题:

export const getServerSideProps = async ({ req, res }) => {
  // 将fetch返回的响应变量改名,避免和入参res重名
  const apiRes = await fetch(`http://localhost:5000/api/posts/`);
  const posts = await apiRes.json();

  return {
    props: {
      token: req.cookies.token,
      posts,
    },
  };
};

2. 配置cookie全局生效规则

js-cookie默认设置的cookie作用域为当前页面路径,如果你在子页面点击设置cookie,该cookie只会在当前子页面生效,服务端渲染或者切换到其他页面时无法读取。设置和删除cookie时都添加path: '/'配置,保证全站生效:

// 设置cookie
cookie.set("token", "ABCD", { path: '/' });
// 删除cookie,需要带相同的配置才能正确删除全局cookie
cookie.remove("token", { path: '/' });

3. 确认getServerSideProps生效范围

你提到之前在_app.js中调用组件,现在改为单独页面调用,需要注意:只有pages目录下的页面级组件声明的getServerSideProps会被Next.js自动执行,普通业务组件中写的getServerSideProps不会触发,所以要确保你现在的代码是写在pages目录下的页面文件里,而不是抽离的公共组件中。

4. 手动解析cookie兜底

如果上述修改后问题依然存在,可以手动从请求头中解析cookie,避免Next.js内置的cookie解析逻辑异常:

export const getServerSideProps = async ({ req, res }) => {
  const apiRes = await fetch(`http://localhost:5000/api/posts/`);
  const posts = await apiRes.json();

  // 手动从请求头解析cookie
  let token = undefined;
  if (req.headers.cookie) {
    const cookieMap = req.headers.cookie.split('; ').reduce((result, item) => {
      const [key, value] = item.split('=');
      result[key] = value;
      return result;
    }, {});
    token = cookieMap.token;
  }

  return {
    props: {
      token,
      posts,
    },
  };
};

5. 验证操作步骤

设置cookie后需要刷新页面才会触发服务端渲染重新执行getServerSideProps,直接点击login按钮仅会修改客户端cookie,不会触发服务端逻辑重新拉取token,所以页面上的token值需要刷新后才会更新。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:36:04