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

部署至Vercel后Cookies返回undefined,checkAuth中间件异常

解决方案:Vercel部署后无法获取Cookies中token的问题

以下是针对本地正常、Vercel部署后无法读取Cookie中token问题的排查和解决步骤:

  • 检查Cookie的SameSite与Secure属性
    生产环境(Vercel)的跨域场景中,Cookie必须满足:

    • SameSite设为None(仅当前后端域名不同时)
    • 同时开启Secure属性(SameSite=None要求HTTPS环境)
      后端设置Cookie的示例代码:
    res.cookie('token', userToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
      maxAge: 7 * 24 * 60 * 60 * 1000
    });
    
  • 修正CORS配置
    后端CORS必须明确指定允许的前端域名(不能用*),同时开启credentials: true,否则前端的withCredentials: true不会生效。以Express为例:

    const cors = require('cors');
    const corsOptions = {
      origin: process.env.FRONTEND_URL,
      credentials: true
    };
    app.use(cors(corsOptions));
    

    若需支持多个域名,可改用动态判断:

    const allowedOrigins = ['https://your-frontend.vercel.app', 'https://another-domain.com'];
    const corsOptions = {
      origin: (origin, callback) => {
        if (!origin || allowedOrigins.includes(origin)) {
          callback(null, true);
        } else {
          callback(new Error('Not allowed by CORS'));
        }
      },
      credentials: true
    };
    
  • 验证Vercel环境变量配置
    确保部署到Vercel时,FRONTEND_URL等关键环境变量已正确设置(不要用本地的localhost:3000),可在Vercel控制台的项目设置中检查环境变量。

  • 检查请求中的Cookie传递
    用浏览器开发者工具的Network面板查看请求头:

    • 确认请求的Cookie字段是否包含token
    • 若未包含,检查Cookie的domain属性是否与当前请求域名匹配(比如前后端为子域名时,需设置domain: '.your-domain.com')
  • 适配Vercel Serverless/Edge函数的Cookie读取方式
    若中间件运行在Vercel的Serverless API路由或Edge函数中,注意读取Cookie的方式:

    • 使用Express框架时,确保已引入cookie-parser中间件:app.use(cookieParser()),之后可通过req.cookies.token读取
    • 手动解析可从请求头提取:
      const parseCookie = (cookieStr, name) => {
        return cookieStr?.split('; ').find(c => c.startsWith(`${name}=`))?.split('=')[1];
      };
      const token = parseCookie(req.headers.cookie, 'token');
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 21:33:22