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

Next.js Server Action请求的Cookie无法在浏览器存储的原因排查

Next.js Server Action登录后JWT Cookie无法存入浏览器的问题

我用Next.js做前端框架、Express做后端,登录流程为:表单提交后通过Next.js Server Action向Express服务器发送POST请求;后端验证凭证通过后,生成JWT令牌并通过res.cookie()写入Cookie。

目前能看到后端响应的Set-Cookie头里确实返回了JWT,但这个Cookie始终无法存入浏览器,导致后续认证请求无法使用该Cookie完成校验。

我已经完成了以下配置排查:

  • 客户端fetch请求中设置了credentials: 'include'(跨域场景下收发Cookie的必要配置)
  • 后端CORS配置正确,指定origin为http://localhost:3000,且credentials设为true
  • 本地采用HTTP运行,Cookie配置了httpOnly: true、secure: false、sameSite: 'Lax'

但问题仍未解决,以下是相关的Server Action代码:

export const loginAction = async (user: z.infer<typeof loginFormSchema>) => {
  try {
    // 验证用户输入字段
    const validateFields = loginFormSchema.safeParse(user);
    if (validateFields.error) throw new Error("Invalid Fields");

    // 向服务器发送请求
    const res = await fetch(`${process.env.SERVER_URL}/api/auth/login`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email: validateFields.data.email,
        password: validateFields.data.password,
      }),
      credentials: "include",
    });
    // 处理服务器响应
    if (!res.ok) {
      const err = await res.text();
      throw new Error(`Failed to log in: ${err}`);
    }
    const data = await res.json();
    const jwt = res.headers.get("set-cookie");
    console.log(jwt);
    // 控制台输出示例:jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY4MDlhZGRlMTQ1MDUzNzViOGE1NWNhNSIsImlhdCI6MTc0NTUwNzk0NCwiZXhwIjoxNzQ2MTEyNzQ0fQ.JRJT6YTfhqYICz6ZZcc6jxKPvGsbTl3RU3R4wwDRW_g; Path=/; HttpOnly; SameSite=Lax
    return data;
  } catch (error) {
    // 错误处理
    if (error instanceof Error) {
      throw new Error(`loginAction error: ${error.message}`);
    } else {
      throw new Error("Unknown error occurred in loginAction.");
    }
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 08:03:19