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

Next.js生产环境设置Cookie值为空问题求助(V15 rc版本)

解决Next.js生产环境Cookie值为空的问题

核心问题:Cookie过期时间计算错误

你的代码里expires参数的时间逻辑有误:Date.now()返回的是毫秒数,但你直接加上了秒数(比如3600),导致Cookie刚设置就会过期(实际过期时间是当前时间+3.6秒),生产环境网络延迟下,客户端还没接收Cookie就失效,最终显示值为空。

修正后的代码

移除冲突的expires参数(保留maxAge即可,Next.js会自动处理过期逻辑),同时优化环境适配:

const cookieStore = cookies();

cookieStore.set({
  name: "accessToken",
  value: res.data?.google?.access,
  httpOnly: true,
  secure: process.env.NODE_ENV === 'production', // 仅生产环境启用secure
  path: "/",
  maxAge: 3600, // 1小时,单位为秒
  sameSite: "lax", // 比strict更兼容,避免跨域场景下的Cookie丢失
});

cookieStore.set({
  name: "refreshToken",
  value: res.data?.google?.refresh,
  httpOnly: true,
  secure: process.env.NODE_ENV === 'production',
  path: "/",
  maxAge: 7 * 24 * 60 * 60, // 7天,单位为秒
  sameSite: "lax",
});

额外排查点

  • HTTPS环境验证:生产环境必须使用HTTPS,否则secure: true会导致浏览器拒绝保存Cookie。如果通过Nginx等反向代理部署,需添加X-Forwarded-Proto头让Next.js识别HTTPS:
    proxy_set_header X-Forwarded-Proto $scheme;
    
  • Next.js配置优化:在next.config.js中开启trustHost,避免跨域或域名配置导致的Cookie问题:
    /** @type {import('next').NextConfig} */
    const nextConfig = {
      trustHost: true,
    };
    
    module.exports = nextConfig;
    
  • API返回值校验:确认生产环境中res.data?.google?.access和res.data?.google?.refresh确实有有效值,排除因接口返回为空导致的Cookie值为空。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 09:42:10