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

Next.js 14中如何为原生Fetch配置服务器端请求代理?

在Next.js 14服务器端为原生fetch配置代理

核心方案:借助代理Agent实现

Node.js原生fetch本身不支持直接配置代理参数,但可以通过http-proxy-agent或https-proxy-agent创建代理实例,传入fetch的agent选项来实现请求走代理。

步骤1:安装依赖

npm install http-proxy-agent https-proxy-agent

步骤2:封装带代理的fetch工具函数

创建可复用的工具函数,仅在服务器端为请求添加代理配置:

import { HttpProxyAgent } from 'http-proxy-agent';
import { HttpsProxyAgent } from 'https-proxy-agent';

// 代理配置,建议通过环境变量动态注入
const PROXY_CONFIG = {
  host: '149.129.239.170',
  port: 8080,
  protocol: 'http:'
};

export async function fetchWithProxy(url, options = {}) {
  // 仅服务器端应用代理逻辑
  if (typeof window === 'undefined') {
    const targetProtocol = new URL(url).protocol;
    const Agent = targetProtocol === 'https:' ? HttpsProxyAgent : HttpProxyAgent;
    const proxyAgent = new Agent(PROXY_CONFIG);

    return fetch(url, {
      ...options,
      agent: proxyAgent
    });
  }

  // 客户端直接使用原生fetch
  return fetch(url, options);
}

步骤3:在服务器端场景使用

在Server Components、API Routes或Server Actions中,用封装后的函数替代原生fetch:

// Server Component示例
export async function UserInfo() {
  const res = await fetchWithProxy('https://api.ipify.org/?format=json');
  const data = await res.json();

  return <div>代理出口IP:{data.ip}</div>;
}

关键注意事项

  • 代理配置优先用环境变量(如process.env.PROXY_HOST),避免硬编码敏感信息
  • 确认代理服务器支持目标请求的协议(HTTP/HTTPS)
  • 通过typeof window === 'undefined'限制代理仅在服务器端生效,客户端请求无需走该代理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:19:51