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

部署在Vercel的Next.js中间件无法读取Cookie求助

解决Next.js Middleware无法跨域读取Cookie的问题

核心问题是跨域场景下Cookie的配置不符合浏览器安全规则,导致浏览器不会将Render后端设置的Cookie发送到Vercel部署的Next.js应用中,最终Middleware读不到Cookie。以下是具体解决方案:

1. 修正后端Cookie配置

你的Node.js后端设置Cookie时,必须添加跨域所需的参数,修改res.cookie代码:

res.cookie('resumaniatoken', token, {
  httpOnly: true,
  secure: true, // 必须开启,因为SameSite: none要求HTTPS
  sameSite: 'none', // 允许跨域发送Cookie
  path: '/' // 确保Cookie在整个域名路径下可用
});
  • sameSite: 'none':允许跨域请求携带Cookie,这是跨域场景的必要配置;
  • secure: true:要求Cookie仅在HTTPS连接下发送,Vercel和Render都默认使用HTTPS,符合要求;
  • path: '/':确保Cookie能被应用的所有路由访问。

2. 前端请求后端时携带Credentials

前端调用后端登录接口时,必须明确设置携带凭证,否则浏览器不会保存或发送Cookie:

  • 用fetch的示例:
fetch('https://your-render-backend-domain.com/api/login', {
  method: 'POST',
  credentials: 'include', // 关键:携带Cookie
  body: JSON.stringify(loginData),
  headers: { 'Content-Type': 'application/json' }
});
  • 用axios的示例:
axios.post('https://your-render-backend-domain.com/api/login', loginData, {
  withCredentials: true // 关键:携带Cookie
});

3. 后端配置CORS允许指定Origin和Credentials

Node.js后端必须配置CORS,允许你的Vercel应用域名,并开启凭证支持:

const cors = require('cors');
app.use(cors({
  origin: 'https://your-vercel-nextjs-domain.vercel.app', // 替换为你的Vercel应用域名
  credentials: true, // 允许携带凭证
}));

注意:不能使用origin: '*',因为浏览器在允许凭证的CORS请求中,不接受通配符Origin。

4. 验证Cookie传递情况

完成上述配置后,用浏览器开发者工具验证:

  1. 登录后,在Application面板的Cookies中确认resumaniatoken的属性:SameSite为None,Secure为true;
  2. 访问受保护路由(如/dashboard)时,查看Network面板中该请求的Request Headers,确认包含Cookie: resumaniatoken=xxx字段。

此时你的Middleware代码中request.cookies.get('resumaniatoken')?.value应该能正确读取到Token,身份校验逻辑即可正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 23:21:23