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

SolidJs中存储Cookie遇问题:如何存储认证返回的JWT令牌?

解决SolidStart中登录后存储JWT到Cookie的问题

你需要修改login路由代码,在认证成功后将JWT令牌写入Cookie,具体步骤如下:

1. 统一Session Storage配置

将createCookieSessionStorage实例移到路由模块顶部复用,确保Cookie名称和routeData中读取的TOKEN_KEY一致:

import {
  Title,
  createCookieSessionStorage,
  parseCookie,
  useNavigate,
} from "solid-start";
// ... 其他导入代码

// 模块顶部创建复用的Session Storage实例
const storage = createCookieSessionStorage({
  cookie: {
    name: TOKEN_KEY, // 和routeData中读取的Cookie名称保持一致
    secure: false, // 生产环境请设为true(仅HTTPS传输)
    secrets: ["je"],
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 30, // 30天有效期
    httpOnly: true, // 禁止前端JS读取,提升安全性
  },
});

// ... 原routeData代码保持不变

2. 在Server Action中存储JWT

修改createServerAction$回调,添加event参数,认证成功后写入Cookie再跳转:

const [submitting, { Form }] = createServerAction$(
  async (form: FormData, { request, fetch, event }) => { // 新增event参数
    const _data: { email: string; password: string } = {
      password: form.get("password") as string,
      email: form.get("email") as string,
    };

    const res = await fetch("http://127.0.0.1:3001/auth/login", {
      credentials: "include",
      body: JSON.stringify({ ..._data }),
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    });
    const data: {
      user: MeType | null;
      error: ErrorType | null;
      jwt: string | null;
    } = await res.json();

    if (data.user && data.jwt) {
      // 将JWT写入响应Cookie
      await storage.setCookie(event, data.jwt);
      throw redirect("/");
    }
    return { data };
  }
);

3. 移除组件内冗余代码

删除Login组件内部创建的const storage = createCookieSessionStorage(...),避免重复创建实例。

关键注意点

  • httpOnly: true能防止XSS攻击窃取令牌,务必保留。
  • 生产环境必须将secure设为true,确保Cookie仅通过HTTPS传输。
  • setCookie是异步方法,必须用await等待执行完成再跳转,否则Cookie可能无法正确设置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 06:10:38