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

Next.js中getServerSideProps无法获取Cookie的问题求助

问题分析与解决方案

你的核心问题是:跨域名部署时,Next.js服务端渲染(getServerSideProps)无法获取浏览器中存储在后端API域名下的httpOnly Cookie。因为浏览器的同源策略,只会将当前请求域名对应的Cookie发送给服务器,Next.js服务器拿到的是自身域名下的Cookie,而非后端API域名的。

以下是针对性的解决步骤:

1. 修正getServerSideProps代码错误

你的代码里存在变量未定义的问题,req应该是context.req,同时不需要在请求头中设置Access-Control-Allow-Credentials(这是响应头)。修正后的代码:

export async function getServerSideProps(context){
 console.log(context.req.headers.cookie);
 console.log(context.req.cookies);

 let user = null;
 try{
    const res = await fetch(`${url}/users/isLoggedin`, {
        method: 'GET',
        credentials: 'include',
        headers: {
            Cookie: context.req.headers.cookie || ''
        },
    });
    const data = await res.json();
    if(!res.ok){
        throw data;
    }
    user = data;   
 }catch(err){
    console.log(err);
 }

 return {
  props: {
    user,
  }
 };
}

2. 统一域名或使用反向代理(推荐)

这是解决跨域Cookie问题的根本方案:

  • 统一域名部署:将Next.js前端和Express后端部署在同一个域名下,用路径区分(比如前端处理/,后端处理/api)。这样后端设置的Cookie域名就是当前域名,浏览器请求Next.js页面时会自动带上Cookie,getServerSideProps就能获取到。
  • Next.js反向代理:在next.config.js中配置反向代理,将前端的/api路径转发到后端API:
module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'https://your-backend-app.herokuapp.com/:path*', // 替换为你的后端Heroku域名
      },
    ];
  },
};

之后前端所有API请求改为/api/xxx,后端设置的Cookie会存储在Next.js域名下,getServerSideProps自然能拿到Cookie。

3. 修正后端Cookie与CORS配置

如果必须保持跨域名部署,需确保Cookie和CORS配置正确:

后端CORS配置

安装cors包并配置,允许前端域名并开启凭证传递:

const cors = require('cors');
app.use(cors({
  origin: 'https://your-nextjs-app.herokuapp.com', // 替换为你的Next.js Heroku域名
  credentials: true,
}));

注意:origin不能设为*,否则无法传递Cookie。

后端Cookie配置

确保Cookie的domain设置为能覆盖前后端域名的通配符(仅限Heroku同主域名的情况):

const cookieOption = {
    expires: new Date(Date.now() + process.env.JWT_COOKIE_EXPIRES_IN*24*60*60*1000),
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production', // 生产环境启用,开发环境设为false
    sameSite: 'none',
    domain: '.herokuapp.com' // 启用该配置,确保子域名共享Cookie
};

4. 验证Cookie存储

登录后,在浏览器开发者工具的Application -> Cookies中检查:

  • 是否存在jwt Cookie
  • Domain是否正确
  • Secure和SameSite是否符合配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:36:18