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
相关产品推荐
相关产品推荐

