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

六边形架构下SvelteKit网关如何安全获取当前请求Cookie?

解决方案

利用Node.js AsyncLocalStorage实现请求上下文隔离

1. 实现请求上下文管理器

在基础设施层创建上下文管理工具,借助Node.js的AsyncLocalStorage存储每个请求的Cookie信息,让网关可直接获取,无需通过应用层传递:

// src/lib/infrastructure/request-context.ts
import { AsyncLocalStorage } from 'node:async_hooks';

type RequestContext = {
  cookies: Record<string, string>;
};

const asyncLocalStorage = new AsyncLocalStorage<RequestContext>();

export const requestContext = {
  run: (cookies: Record<string, string>, callback: () => Promise<void> | void) => {
    return asyncLocalStorage.run({ cookies }, callback);
  },
  getCookies: () => {
    const context = asyncLocalStorage.getStore();
    return context?.cookies ?? {};
  }
};

2. 在Load函数中初始化上下文

在服务器端load函数里,将当前请求的Cookie注入上下文,确保后续异步调用链能访问到:

// +page.server.ts
import { requestContext } from '$lib/infrastructure/request-context';
import { yourDataUseCase } from '$lib/application/use-cases';

export async function load({ cookies }) {
  let data;
  await requestContext.run(cookies, async () => {
    data = await yourDataUseCase.execute();
  });
  return { data };
}

3. 网关中直接获取Cookie

在网关类里,通过上下文管理器拿到当前请求的Cookie,发起外部API请求:

// src/lib/infrastructure/gateways/external-api-gateway.ts
import { requestContext } from '../request-context';

export class ExternalApiGateway {
  async fetchRequiredData() {
    const cookies = requestContext.getCookies();
    const cookieHeader = Object.entries(cookies)
      .map(([key, value]) => `${key}=${value}`)
      .join('; ');

    const response = await fetch('https://your-external-api.com/endpoint', {
      headers: {
        Cookie: cookieHeader
      }
    });

    if (!response.ok) throw new Error('Failed to fetch external data');
    return response.json();
  }
}

关键优势

  • 架构合规:应用层完全无需感知Cookie这类基础设施细节,保持六边形架构的边界清晰;
  • 请求隔离:AsyncLocalStorage会自动在每个请求的异步链路中维护独立上下文,Node.js服务器上不会出现用户数据共享问题;
  • 低侵入性:仅需在基础设施层添加上下文管理逻辑,无需修改应用层的用例、处理类代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:33:32