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

NextJS如何创建服务端请求上下文以转发请求头

在Next.js中通过AsyncLocalStorage实现请求头转发的可行方案

你的方案完全可行,只需调整细节适配Next.js的运行时特性,就能摆脱手动传参的繁琐:

一、解决AsyncLocalStorage构建错误

  • 无需手动安装async_hooks,它是Node.js内置模块,Next.js默认支持(前提是使用Node.js运行时)。之前手动引入导致的构建问题,直接移除相关依赖即可。
  • 确认项目使用Node.js运行时:Next.js默认使用该运行时,若配置了Edge Runtime需改回,因为AsyncLocalStorage不支持Edge环境。

二、修正代码实现

1. 上下文定义(context.ts)

import { AsyncLocalStorage } from 'async_hooks';

// 存储目标请求头的值,类型按需调整
export const requestContext = new AsyncLocalStorage<string | undefined>();

2. Middleware配置(middleware.ts)

注意App Router下的Middleware默认用Edge Runtime,需手动指定为Node.js,否则无法使用AsyncLocalStorage:

// 顶部指定运行时
export const config = {
  runtime: 'nodejs',
};

import { NextRequest, NextResponse } from 'next/server';
import { requestContext } from './context';

const SOME_HEADER = 'X-Custom-Header'; // 替换为你的目标请求头

export function middleware(request: NextRequest) {
  const headerValue = request.headers.get(SOME_HEADER);
  return requestContext.run(headerValue, () => NextResponse.next());
}

3. 外部API客户端(client.ts)

在getServerSideProps或API Routes中调用外部API时,直接从上下文取值:

import axios from 'axios';
import { requestContext } from './context';

const EXTERNAL_API = 'https://your-external-api.com/endpoint';
const SOME_HEADER = 'X-Custom-Header'; // 与middleware中保持一致

export async function callExternalApi(data: any) {
  const headerValue = requestContext.getStore();
  return axios.post(EXTERNAL_API, data, {
    headers: {
      [SOME_HEADER]: headerValue,
    },
  });
}

三、关键注意事项

  • Pages Router场景:getServerSideProps会自动继承Middleware设置的上下文,无需额外配置。
  • API Routes:确保未配置Edge Runtime,保持默认Node.js运行时。
  • 异步边界:所有需要访问上下文的代码需在requestContext.run的执行链中,异步任务只要在该链内启动,上下文会自动保留。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:01:09