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

Express与NextJS跨域Cookie问题:Chrome拦截及读取失败

跨域Cookie相关问题与解决方案

问题1:Express res.cookie设置带Partitioned属性的Cookie被Chrome拦截

场景

在Vercel分别部署A域名的Node/Express API和B域名的Next.js 14(App Router)应用,登录时API生成JWT并通过名为token的Cookie返回给前端。

问题描述

最初使用Express的res.cookie方法设置Cookie时,会被Chrome拦截。需添加Partitioned属性才能正常存储,但Express的res.cookie不支持该属性。

解决方案

改用res.setHeader手动构造Set-Cookie响应头,明确包含所有必要属性(包括Partitioned)。修改后的登录接口代码如下:

const login = async (req, res, next) => {
    const { pseudo, password } = req.body;

    if (!pseudo || !password) {
        return res.status(401).json({ message: 'Pseudo and password are required' });
    }
    
    try {
        // 检查用户是否存在
        const user = await UserModel.findOne({ pseudo }).lean().exec();
        if (!user) {
            return res.status(401).json({ message: 'Pseudo or password is wrong' });
        }

        // 验证密码
        const passwordValid = await bcrypt.compare(password, user.password);
        if (!passwordValid) {
            return res.status(401).json({ message: 'Pseudo or password is wrong' });
        }

        // 生成JWT(有效期1天)
        const token = jwt.sign({ pseudo }, SECRET_TOKEN, { expiresIn: '1d' });

        // 手动设置Cookie头,包含Partitioned属性
        res.setHeader('Set-Cookie', `token=${token}; Max-Age=${3600 * 24}; Path=/; HttpOnly; SameSite=None; Secure; Partitioned;`)
        // 原res.cookie方法因不支持Partitioned被注释
        //res.cookie('token', token, { maxAge: 3600 * 24 * 1000, httpOnly: true, sameSite: 'none', secure: true, partitioned: true });

        res.status(200).json({ message: 'Login successful', user: user.pseudo });
    } catch (error) {
        next(error);
    }
}

场景

Next.js应用的/admin页面通过app/admin/layout.js做身份校验,代码尝试通过cookieStore.get('token')获取Cookie,但返回undefined,尽管浏览器中已存在该Cookie。

解决思路

  1. 检查Cookie的Domain属性

    • 由于API和Next.js应用分属不同域名,若设置Cookie时未指定Domain,浏览器会默认将Cookie绑定到API的域名A,导致Next.js的域名B无法读取。
    • 若两个域名属于同主域的子域名(如api.example.com和app.example.com),需在Set-Cookie头中添加Domain=.example.com;若为完全独立域名,跨域Cookie受浏览器限制,可考虑登录成功后将Token返回给前端并存入localStorage,后续请求通过Authorization头传递。
  2. 验证Cookie的Path属性

    • 确保Cookie的Path设置为/,保证应用所有路径都能访问该Cookie。
  3. 排查Partitioned属性的隔离影响

    • Partitioned属性会将Cookie隔离在站点分区中,需确认Next.js应用的请求是否处于同一分区。可在浏览器开发者工具的Application面板中查看Cookie的存储分区是否与当前站点匹配。
  4. 确认Next.js Server Component中Cookie的传递

    • 在App Router的Server Component中使用cookies()是正确的,但需验证客户端跳转至/admin时,请求头是否携带了Cookie字段。可通过浏览器Network面板查看/admin请求的Request Headers是否包含Cookie: token=xxx。
  5. 检查HTTPS环境与Secure属性

    • 由于Secure属性要求Cookie仅在HTTPS环境下传输,确认Vercel部署的应用均使用HTTPS,避免因环境问题导致Cookie无法被读取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 06:13:19