express-http-proxy vs http-proxy vs http-proxy-agent vs http-proxy-middleware vs proxy-middleware
Node.js 代理中间件技术选型与架构对比
express-http-proxyhttp-proxyhttp-proxy-agenthttp-proxy-middlewareproxy-middleware

Node.js 代理中间件技术选型与架构对比

http-proxy 是 Node.js 生态中最基础的 HTTP 代理库,提供底层代理服务器能力。http-proxy-middleware 是基于 http-proxy 封装的 Express/Connect 中间件,简化了集成流程。express-http-proxy 是另一个 Express 专用的代理中间件,采用不同的实现方式。http-proxy-agent 用途完全不同,它是用于让 HTTP 客户端请求通过代理服务器转发的 Agent,而非创建代理服务器。proxy-middleware 是较早期的代理中间件方案,目前维护状态不佳。这些包在架构层级、使用场景和维护状态上有显著差异。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
express-http-proxy01,249150 kB1461 年前MIT
http-proxy014,118-6196 年前MIT
http-proxy-agent01,16717.6 kB415 个月前MIT
http-proxy-middleware011,12697.4 kB1513 天前MIT
proxy-middleware0143-2111 年前MIT

Node.js 代理中间件技术选型与架构对比

在 Node.js 开发生态中,HTTP 代理是常见的基础设施需求。无论是开发环境的 API 转发、生产环境的微服务网关,还是企业网络中的代理隧道,都需要选择合适的代理方案。本文对比五个常见的 npm 代理包,帮助你做出正确的架构决策。

🏗️ 核心定位:代理服务器 vs 代理客户端

首先需要明确一个关键区别:这些包分为两类完全不同的用途。

http-proxy、http-proxy-middleware、express-http-proxy、proxy-middleware 都是用于创建代理服务器,接收客户端请求并转发到目标服务器。

http-proxy-agent 则是代理客户端,让你的 HTTP 请求通过已有的代理服务器转发。

// http-proxy: 创建代理服务器
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
proxy.listen(8080);

// http-proxy-agent: 让请求通过代理服务器
const HttpProxyAgent = require('http-proxy-agent');
const agent = new HttpProxyAgent('http://proxy.example.com:8080');
fetch('https://api.example.com', { agent });

🔧 基础用法对比

http-proxy - 底层代理服务器

const httpProxy = require('http-proxy');
const http = require('http');

const proxy = httpProxy.createProxyServer({
  target: 'http://backend.example.com',
  changeOrigin: true
});

http.createServer((req, res) => {
  proxy.web(req, res);
}).listen(3000);

http-proxy-middleware - Express 中间件封装

const { createProxyMiddleware } = require('http-proxy-middleware');
const express = require('express');

const app = express();

app.use('/api', createProxyMiddleware({
  target: 'http://backend.example.com',
  changeOrigin: true
}));

app.listen(3000);

express-http-proxy - Express 专用中间件

const proxy = require('express-http-proxy');
const express = require('express');

const app = express();

app.use('/api', proxy('http://backend.example.com', {
  preserveHostHdr: true,
  proxyReqPathResolver: (req) => `/api${req.url}`
}));

app.listen(3000);

proxy-middleware - 早期中间件方案

const proxy = require('proxy-middleware');
const express = require('express');
const url = require('url');

const app = express();

app.use('/api', proxy(url.parse('http://backend.example.com/api')));

app.listen(3000);

http-proxy-agent - 代理客户端 Agent

const HttpProxyAgent = require('http-proxy-agent');
const https = require('https');

const agent = new HttpProxyAgent('http://proxy.example.com:8080');

const options = {
  hostname: 'api.example.com',
  port: 443,
  path: '/data',
  method: 'GET',
  agent: agent
};

const req = https.request(options, (res) => {
  // 处理响应
});

req.end();

🔄 请求拦截与修改能力

http-proxy - 事件驱动的低级控制

const proxy = httpProxy.createProxyServer({
  target: 'http://backend.example.com'
});

proxy.on('proxyReq', (proxyReq, req, res) => {
  // 修改转发前的请求头
  proxyReq.setHeader('X-Custom-Header', 'value');
  proxyReq.setHeader('X-Forwarded-For', req.ip);
});

proxy.on('proxyRes', (proxyRes, req, res) => {
  // 修改返回的响应头
  proxyRes.headers['X-Powered-By'] = 'MyProxy';
});

http-proxy-middleware - 中间件风格的配置

app.use('/api', createProxyMiddleware({
  target: 'http://backend.example.com',
  onProxyReq: (proxyReq, req, res) => {
    proxyReq.setHeader('X-Custom-Header', 'value');
  },
  onProxyRes: (proxyRes, req, res) => {
    proxyRes.headers['X-Powered-By'] = 'MyProxy';
  }
}));

express-http-proxy - Promise 风格的过滤器

app.use('/api', proxy('http://backend.example.com', {
  filter: (req, res) => {
    // 返回 false 可阻止某些请求转发
    return req.headers['authorization'] !== undefined;
  },
  proxyReqPathResolver: (req) => {
    return `/v1${req.url}`;
  },
  userResDecorator: (proxyRes, proxyResData, userReq, userRes) => {
    // 修改响应数据
    const data = JSON.parse(proxyResData.toString());
    return JSON.stringify({ ...data, processed: true });
  }
}));

proxy-middleware - 有限的配置选项

// proxy-middleware 配置能力较弱
app.use('/api', proxy(url.parse('http://backend.example.com/api')));
// 不支持细粒度的请求/响应拦截

http-proxy-agent - 不适用

// http-proxy-agent 不处理请求拦截
// 它仅负责将请求路由到代理服务器
const agent = new HttpProxyAgent('http://proxy.example.com:8080');
// 请求修改需在 fetch/https.request 层面处理

🔌 WebSocket 支持对比

http-proxy - 原生 WebSocket 支持

const proxy = httpProxy.createProxyServer({
  target: 'ws://backend.example.com',
  ws: true
});

const server = http.createServer();

server.on('upgrade', (req, socket, head) => {
  proxy.ws(req, socket, head);
});

server.listen(3000);

http-proxy-middleware - 支持 WebSocket

app.use('/ws', createProxyMiddleware({
  target: 'ws://backend.example.com',
  ws: true,
  changeOrigin: true
}));

express-http-proxy - 不支持 WebSocket

// express-http-proxy 不支持 WebSocket 转发
// 需要配合其他库如 'ws' 手动实现
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });
// 需自行编写 WebSocket 代理逻辑

proxy-middleware - 不支持 WebSocket

// proxy-middleware 仅支持 HTTP/HTTPS
// 无 WebSocket 转发能力

http-proxy-agent - 不适用

// http-proxy-agent 用于 HTTP 客户端请求
// WebSocket 需使用其他 Agent 如 'socks-proxy-agent'

⚠️ 维护状态与风险提示

已确认的维护状态

包名维护状态建议
http-proxy活跃维护✅ 可用于新项目
http-proxy-middleware活跃维护✅ 强烈推荐
express-http-proxy维护中但较慢⚠️ 谨慎使用
proxy-middleware基本停止维护❌ 不建议新项目使用
http-proxy-agent活跃维护✅ 特定场景必需

proxy-middleware 弃用警告

// ❌ 不建议在新项目中使用
const proxy = require('proxy-middleware');

// ✅ 推荐替代方案
const { createProxyMiddleware } = require('http-proxy-middleware');

🎯 实际场景选型指南

场景一:开发环境 API 转发

// 推荐:http-proxy-middleware
// 理由:配置简单,Express 集成好,文档完善
const { createProxyMiddleware } = require('http-proxy-middleware');

app.use('/api', createProxyMiddleware({
  target: 'http://localhost:8080',
  changeOrigin: true,
  logLevel: 'debug'
}));

场景二:独立反向代理服务器

// 推荐:http-proxy
// 理由:不依赖框架,可独立部署,支持 WebSocket
const httpProxy = require('http-proxy');

const proxy = httpProxy.createProxyServer({
  target: 'http://backend.example.com',
  ws: true
});

proxy.listen(80);

场景三:企业网络代理隧道

// 推荐:http-proxy-agent
// 理由:专门用于客户端通过代理服务器访问外部 API
const HttpProxyAgent = require('http-proxy-agent');
const axios = require('axios');

const agent = new HttpProxyAgent('http://corporate-proxy:8080');

axios.get('https://external-api.com/data', {
  httpAgent: agent,
  httpsAgent: agent
});

场景四:微服务网关(需要响应修改)

// 推荐:express-http-proxy
// 理由:userResDecorator 方便修改响应数据
const proxy = require('express-http-proxy');

app.use('/gateway', proxy('http://microservice:3000', {
  userResDecorator: (proxyRes, proxyResData) => {
    const data = JSON.parse(proxyResData.toString());
    return JSON.stringify({
      ...data,
      gatewayTimestamp: Date.now()
    });
  }
}));

场景五:遗留项目维护

// 仅在维护旧代码时使用 proxy-middleware
// 新代码应迁移到 http-proxy-middleware
const proxy = require('proxy-middleware');
const url = require('url');

app.use('/legacy', proxy(url.parse('http://old-backend/api')));

📊 功能对比总览

功能特性http-proxyhttp-proxy-middlewareexpress-http-proxyproxy-middlewarehttp-proxy-agent
创建代理服务器✅✅✅✅❌
Express 中间件❌✅✅✅❌
WebSocket 支持✅✅❌❌❌
请求拦截✅ (事件)✅ (回调)✅ (过滤器)❌❌
响应修改✅ (事件)✅ (回调)✅ (decorator)❌❌
代理客户端❌❌❌❌✅
维护状态活跃活跃一般停止活跃

💡 架构决策建议

首选方案:对于大多数 Express 项目,http-proxy-middleware 是最佳选择。它基于成熟的 http-proxy,提供了友好的中间件接口,社区活跃,文档完善。

底层需求:如果需要创建独立的代理服务器或不使用 Express,直接使用 http-proxy。它提供了最完整的控制能力。

特殊场景:http-proxy-agent 用途完全不同,仅在需要让客户端请求通过代理服务器时使用。

避免使用:proxy-middleware 已不再推荐用于新项目。express-http-proxy 可以作为备选,但优先评估 http-proxy-middleware 是否能满足需求。

🔒 安全注意事项

// 所有代理方案都需要注意安全问题

// 1. 限制可代理的目标
app.use('/api', createProxyMiddleware({
  target: 'http://trusted-backend.com',
  // 不要允许用户控制 target
}));

// 2. 验证转发请求
app.use('/api', createProxyMiddleware({
  target: 'http://backend.com',
  filter: (req, res) => {
    // 验证用户权限
    return req.user && req.user.role === 'admin';
  }
}));

// 3. 设置适当的超时
app.use('/api', createProxyMiddleware({
  target: 'http://backend.com',
  timeout: 30000,
  proxyTimeout: 30000
}));

📌 总结

选择代理方案时,先明确你的核心需求:是创建代理服务器还是让请求通过代理?需要 Express 集成吗?需要 WebSocket 支持吗?

对于 90% 的 Express 项目,http-proxy-middleware 是最稳妥的选择。对于独立代理服务器,http-proxy 提供最大灵活性。对于企业代理隧道,http-proxy-agent 是专用工具。

避免在新项目中使用 proxy-middleware,并在可能的情况下将遗留代码迁移到更现代的方案。

如何选择: express-http-proxy vs http-proxy vs http-proxy-agent vs http-proxy-middleware vs proxy-middleware

  • express-http-proxy:

    选择 express-http-proxy 如果你需要 Express 专用的代理中间件,且希望使用 Promise 风格的 API 处理请求过滤和响应修改。它适合需要精细控制请求转发逻辑的场景,如微服务网关或 API 聚合层。但需注意其维护活跃度不如 http-proxy-middleware。

  • http-proxy:

    选择 http-proxy 如果你需要底层代理服务器能力,不依赖 Express 框架,或需要创建独立的代理服务器进程。它适合构建反向代理服务器、负载均衡器或需要 WebSocket 支持的高级场景。这是其他中间件包的基础依赖。

  • http-proxy-agent:

    选择 http-proxy-agent 如果你的应用需要让出站 HTTP 请求通过企业代理服务器转发,而不是创建代理服务器。它常用于爬虫、企业内部网络访问或需要配置代理隧道的场景。用途与其他四个包完全不同。

  • http-proxy-middleware:

    选择 http-proxy-middleware 如果你在 Express 或 Connect 项目中需要快速集成代理功能,且希望获得活跃的社区支持和文档。它是目前最推荐的 Express 代理中间件方案,适合开发环境代理、API 网关和微服务路由。

  • proxy-middleware:

    不建议在新项目中选择 proxy-middleware。该包维护状态不佳,功能已被 http-proxy-middleware 等更现代的包替代。仅在维护遗留项目时考虑使用,新项目应评估其他替代方案。

express-http-proxy的README

express-http-proxy NPM version Build Status

Express middleware to proxy request to another host and pass response back to original caller.

Install

$ npm install express-http-proxy --save

Usage

proxy(host, options);

Example:

To proxy URLS starting with '/proxy' to the host 'www.google.com':

var proxy = require('express-http-proxy');
var app = require('express')();

app.use('/proxy', proxy('www.google.com'));

30k view

The proxy middleware:

  • proxies request to your server to an arbitrary server, and
  • provide hooks to decorate and filter requests to the proxy target, and
  • provide hooks you to decorate and filter proxy responses before returning them to the client.

Client                    Express App                Proxy Middleware                Target Server
  |                           |                            |                             |
  | HTTP Request              |                            |                             |
  |-------------------------->|                            |                             |
  |                           | Request                    |                             |
  |                           |--------------------------->|                             |
  |                           |                            | +------------------------+  |
  |                           |                            | | Request Preprocessing  |  |
  |                           |                            | | 1. filter requests     |  |
  |                           |                            | | 2. resolve proxy host  |  |
  |                           |                            | | 3. decorate proxy opts |  |
  |                           |                            | | 4. decorate proxy req  |  |
  |                           |                            | | 5. resolve req path    |  |
  |                           |                            | +------------------------+  |
  |                           |                            | Forwarded Request           |
  |                           |                            |---------------------------->|
  |                           |                            |                             |
  |                           |                            | Response with Headers       |
  |                           |                            |<----------------------------|
  |                           |                            |                             |
  |                           |                            | +------------------------+  |
  |                           |                            | | Response Processing    |  |
  |                           |                            | | 1. skip to next?       |  |
  |                           |                            | | 2. copy proxy headers  |  |
  |                           |                            | | 3. decorate headers    |  |
  |                           |                            | | 4. decorate response   |  |
  |                           |                            | +------------------------+  |
  |                           |                            |                             |
  |                           | Modified Response          |                             |
  |                           |<---------------------------|                             |
  | Final Response            |                            |                             |
  |<--------------------------|                            |                             |
  |                           |                            |                             |

Streaming

Proxy requests and user responses are piped/streamed/chunked by default.

If you define a response modifier (userResDecorator, userResHeaderDecorator), or need to inspect the response before continuing (maybeSkipToNext), streaming is disabled, and the request and response are buffered. This can cause performance issues with large payloads.

Promises

Many function hooks support Promises. If any Promise is rejected, next(x) is called in the hosting application, where x is whatever you pass to Promise.reject;

e.g.

  app.use(proxy('/reject-promise', {
    proxyReqOptDecorator: function() {
      return Promise.reject('An arbitrary rejection message.');
    }
  }));

eventually calls

next('An arbitrary rejection messasage');

Host

The first positional argument is for the proxy host; in many cases you will use a static string here, eg.

app.use('/', proxy('http://google.com'))

However, this argument can also be a function, and that function can be memoized or computed on each request, based on the setting of memoizeHost.

function selectProxyHost() {
  return (new Date() % 2) ? 'http://google.com' : 'http://altavista.com';
}

app.use('/', proxy(selectProxyHost));

Notie: Host is only the host name. Any params after in url will be ignored. For http://google.com/myPath`, myPathwill be ignored because the host name isgoogle.com. See proxyReqPathResolver`` for more detailed path information.

Middleware mixing

If you use 'https://www.npmjs.com/package/body-parser' you should declare it AFTER the proxy configuration, otherwise original 'POST' body could be modified and not proxied correctly.

app.use('/proxy', proxy('http://foo.bar.com'))

// Declare use of body-parser AFTER the use of proxy
app.use(bodyParser.foo(bar))
app.use('/api', ...)

If this cannot be avoided and you MUST proxy after body-parser has been registered, set parseReqBody to false and explicitly specify the body you wish to send in proxyReqBodyDecorator.

app.use(bodyParser.foo(bar))

app.use('/proxy', proxy('http://foo.bar.com', {
  parseReqBody: false,
  proxyReqBodyDecorator: function () {

  },
}))

Options

proxyReqPathResolver (supports Promises)

Note: In express-http-proxy, the path is considered the portion of the url after the host, and including all query params. E.g. for the URL http://smoogle.com/search/path?q=123; the path is /search/path?q=123. Authors using this resolver must also handle the query parameter portion of the path.

Provide a proxyReqPathResolver function if you'd like to operate on the path before issuing the proxy request. Use a Promise for async operations.

  app.use(proxy('localhost:12345', {
    proxyReqPathResolver: function (req) {
      var parts = req.url.split('?');
      var queryString = parts[1];
      var updatedPath = parts[0].replace(/test/, 'tent');
      return updatedPath + (queryString ? '?' + queryString : '');
    }
  }));

Promise form

app.use('/proxy', proxy('localhost:12345', {
  proxyReqPathResolver: function(req) {
    return new Promise(function (resolve, reject) {
      setTimeout(function () {   // simulate async
        var parts = req.url.split('?');
        var queryString = parts[1];
        var updatedPath = parts[0].replace(/test/, 'tent');
        var resolvedPathValue = updatedPath + (queryString ? '?' + queryString : '');
        resolve(resolvedPathValue);
      }, 200);
    });
  }
}));

forwardPath

DEPRECATED. See proxyReqPathResolver

forwardPathAsync

DEPRECATED. See proxyReqPathResolver

filter (supports Promises)

The filter option can be used to limit what requests are proxied. Return true to continue to execute proxy; return false-y to skip proxy for this request.

For example, if you only want to proxy get request:

app.use('/proxy', proxy('www.google.com', {
  filter: function(req, res) {
     return req.method == 'GET';
  }
}));

Promise form:

  app.use(proxy('localhost:12346', {
    filter: function (req, res) {
      return new Promise(function (resolve) {
        resolve(req.method === 'GET');
      });
    }
  }));

Note that in the previous example, resolve(false) will execute the happy path for filter here (skipping the rest of the proxy, and calling next()). reject() will also skip the rest of proxy and call next().

userResDecorator (was: intercept) (supports Promise)

You can modify the proxy's response before sending it to the client.

app.use('/proxy', proxy('www.google.com', {
  userResDecorator: function(proxyRes, proxyResData, userReq, userRes) {
    data = JSON.parse(proxyResData.toString('utf8'));
    data.newProperty = 'exciting data';
    return JSON.stringify(data);
  }
}));
app.use(proxy('httpbin.org', {
  userResDecorator: function(proxyRes, proxyResData) {
    return new Promise(function(resolve) {
      proxyResData.funkyMessage = 'oi io oo ii';
      setTimeout(function() {
        resolve(proxyResData);
      }, 200);
    });
  }
}));
304 - Not Modified

When your proxied service returns 304, not modified, this step will be skipped, since there is no body to decorate.

exploiting references

The intent is that this be used to modify the proxy response data only.

Note: The other arguments (proxyRes, userReq, userRes) are passed by reference, so you can currently exploit this to modify either response's headers, for instance, but this is not a reliable interface. I expect to close this exploit in a future release, while providing an additional hook for mutating the userRes before sending.

gzip responses

If your proxy response is gzipped, this program will automatically unzip it before passing to your function, then zip it back up before piping it to the user response. There is currently no way to short-circuit this behavior.

limit

This sets the body size limit (default: 1mb). If the body size is larger than the specified (or default) limit, a 413 Request Entity Too Large error will be returned. See bytes.js for a list of supported formats.

app.use('/proxy', proxy('www.google.com', {
  limit: '5mb'
}));

memoizeHost

Defaults to true.

When true, the host argument will be parsed on first request, and memoized for subsequent requests.

When false, host argument will be parsed on each request.

E.g.,


  function coinToss() { return Math.random() > .5 }
  function getHost() { return coinToss() ? 'http://yahoo.com' : 'http://google.com' }

  app.use(proxy(getHost, {
    memoizeHost: false
  }))

In this example, when memoizeHost:false, the coinToss occurs on each request, and each request could get either value.

Conversely, When memoizeHost:true, the coinToss would occur on the first request, and all additional requests would return the value resolved on the first request.

userResHeaderDecorator

When a userResHeaderDecorator is defined, the return of this method will replace (rather than be merged on to) the headers for userRes.

Note that by default, headers from the PROXY response CLOBBER all headers that may have previously been set on the userResponse. Authors have the option of constructing any combination of proxyRes and userRes headers in the userResHeaderDecorator. Check the tests for this method for examples.

app.use('/proxy', proxy('www.google.com', {
  userResHeaderDecorator(headers, userReq, userRes, proxyReq, proxyRes) {
    // recieves an Object of headers, returns an Object of headers.
    return headers;
  }
}));

decorateRequest

REMOVED: See proxyReqOptDecorator and proxyReqBodyDecorator.

skipToNextHandlerFilter(supports Promise form)

(experimental: this interface may change in upcoming versions)

Allows you to inspect the proxy response, and decide if you want to continue processing (via express-http-proxy) or call next() to return control to express.

app.use('/proxy', proxy('www.google.com', {
  skipToNextHandlerFilter: function(proxyRes) {
    return proxyRes.statusCode === 404;
  }
}));

proxyErrorHandler

By default, express-http-proxy will pass any errors except ECONNRESET to next, so that your application can handle or react to them, or just drop through to your default error handling. ECONNRESET errors are immediately returned to the user for historical reasons.

If you would like to modify this behavior, you can provide your own proxyErrorHandler.

// Example of skipping all error handling.

app.use(proxy('localhost:12346', {
  proxyErrorHandler: function(err, res, next) {
    next(err);
  }
}));


// Example of rolling your own

app.use(proxy('localhost:12346', {
  proxyErrorHandler: function(err, res, next) {
    switch (err && err.code) {
      case 'ECONNRESET':    { return res.status(405).send('504 became 405'); }
      case 'ECONNREFUSED':  { return res.status(200).send('gotcher back'); }
      default:              { next(err); }
    }
}}));

proxyReqOptDecorator (supports Promise form)

You can override most request options before issuing the proxyRequest. proxyReqOpt represents the options argument passed to the (http|https).request module.

NOTE: req.path cannot be changed via this method; use proxyReqPathResolver instead. (see https://github.com/villadora/express-http-proxy/issues/243)

app.use('/proxy', proxy('www.google.com', {
  proxyReqOptDecorator: function(proxyReqOpts, srcReq) {
    // you can update headers
    proxyReqOpts.headers['Content-Type'] = 'text/html';
    // you can change the method
    proxyReqOpts.method = 'GET';
    return proxyReqOpts;
  }
}));

You can use a Promise for async style.

app.use('/proxy', proxy('www.google.com', {
  proxyReqOptDecorator: function(proxyReqOpts, srcReq) {
    return new Promise(function(resolve, reject) {
      proxyReqOpts.headers['Content-Type'] = 'text/html';
      resolve(proxyReqOpts);
    })
  }
}));

proxyReqBodyDecorator (supports Promise form)

You can mutate the body content before sending the proxyRequest.

app.use('/proxy', proxy('www.google.com', {
  proxyReqBodyDecorator: function(bodyContent, srcReq) {
    return bodyContent.split('').reverse().join('');
  }
}));

You can use a Promise for async style.

app.use('/proxy', proxy('www.google.com', {
  proxyReqBodyDecorator: function(proxyReq, srcReq) {
    return new Promise(function(resolve, reject) {
      http.get('http://dev/null', function (err, res) {
        if (err) { reject(err); }
        resolve(res);
      });
    })
  }
}));

https

Normally, your proxy request will be made on the same protocol as the host parameter. If you'd like to force the proxy request to be https, use this option.

app.use('/proxy', proxy('www.google.com', {
  https: true
}));

preserveHostHdr

You can copy the host HTTP header to the proxied express server using the preserveHostHdr option.

app.use('/proxy', proxy('www.google.com', {
  preserveHostHdr: true
}));

parseReqBody

The parseReqBody option allows you to control parsing the request body. For example, disabling body parsing is useful for large uploads where it would be inefficient to hold the data in memory.

Note: this setting is required for binary uploads. A future version of this library may handle this for you.

This defaults to true in order to preserve legacy behavior.

When false, no action will be taken on the body and accordingly req.body will no longer be set.

Note that setting this to false overrides reqAsBuffer and reqBodyEncoding below.

app.use('/proxy', proxy('www.google.com', {
  parseReqBody: false
}));

reqAsBuffer

Note: this is an experimental feature. ymmv

The reqAsBuffer option allows you to ensure the req body is encoded as a Node Buffer when sending a proxied request. Any value for this is truthy.

This defaults to to false in order to preserve legacy behavior. Note that the value of reqBodyEnconding is used as the encoding when coercing strings (and stringified JSON) to Buffer.

Ignored if parseReqBody is set to false.

app.use('/proxy', proxy('www.google.com', {
  reqAsBuffer: true
}));

reqBodyEncoding

Encoding used to decode request body. Defaults to utf-8.

Use null to preserve as Buffer when proxied request body is a Buffer. (e.g image upload) Accept any values supported by raw-body.

The same encoding is used in the intercept method.

Ignored if parseReqBody is set to false.

app.use('/post', proxy('httpbin.org', {
  reqBodyEncoding: null
}));

timeout

By default, node does not express a timeout on connections. Use timeout option to impose a specific timeout. Timed-out requests will respond with 504 status code and a X-Timeout-Reason header.

app.use('/', proxy('httpbin.org', {
  timeout: 2000  // in milliseconds, two seconds
}));

Trace debugging

The node-debug module is used to provide a trace debugging capability.

DEBUG=express-http-proxy npm run YOUR_PROGRAM
DEBUG=express-http-proxy npm run YOUR_PROGRAM  | grep 'express-http-proxy'   # to filter down to just these messages

Will trace the execution of the express-http-proxy module in order to aide debugging.

Upgrade to 1.0, transition guide and breaking changes

decorateRequest has been REMOVED, and will generate an error when called. See proxyReqOptDecorator and proxyReqBodyDecorator.

Resolution: Most authors will simply need to change the method name for their decorateRequest method; if author was decorating reqOpts and reqBody in the same method, this will need to be split up.

intercept has been REMOVED, and will generate an error when called. See userResDecorator.

Resolution: Most authors will simply need to change the method name from intercept to userResDecorator, and exit the method by returning the value, rather than passing it to a callback. E.g.:

Before:

app.use('/proxy', proxy('www.google.com', {
  intercept: function(proxyRes, proxyResData, userReq, userRes, cb) {
    data = JSON.parse(proxyResData.toString('utf8'));
    data.newProperty = 'exciting data';
    cb(null,  JSON.stringify(data));
  }
}));

Now:

app.use('/proxy', proxy('www.google.com', {
  userResDecorator: function(proxyRes, proxyResData, userReq, userRes) {
    data = JSON.parse(proxyResData.toString('utf8'));
    data.newProperty = 'exciting data';
    return JSON.stringify(data);
  }
}));

forwardPath and forwardPathAsync have been DEPRECATED and will generate a warning when called. See proxyReqPathResolver.

Resolution: Simple update the name of either forwardPath or forwardPathAsync to proxyReqPathResolver.

When errors occur on your proxy server

When your proxy server responds with an error, express-http-proxy returns a response with the same status code. See test/catchingErrors for syntax details.

When your proxy server times out, express-http-proxy will continue to wait indefinitely for a response, unless you define a timeout as described above.

Questions

Q: Does it support https proxy?

The library will automatically use https if the provided path has 'https://' or ':443'. You may also set option https to true to always use https.

You can use proxyReqOptDecorator to ammend any auth or challenge headers required to succeed https.

Q: How can I support non-standard certificate chains?

You can use the ability to decorate the proxy request prior to sending. See proxyReqOptDecorator for more details.

app.use('/', proxy('internalhost.example.com', {
  proxyReqOptDecorator: function(proxyReqOpts, originalReq) {
    proxyReqOpts.ca =  [caCert, intermediaryCert]
    return proxyReqOpts;
  }
})

Q: How to ignore self-signed certificates ?

You can set the rejectUnauthorized value in proxy request options prior to sending. See proxyReqOptDecorator for more details.

app.use('/', proxy('internalhost.example.com', {
  proxyReqOptDecorator: function(proxyReqOpts, originalReq) {
    proxyReqOpts.rejectUnauthorized = false
    return proxyReqOpts;
  }
}))

Release Notes

ReleaseNotes
2.1.2Fixes => content-length request header is removed when parseReqBody is false (#549), implement memory leak fix (#566), fix to UserDecorator, replace httpbin in test suite, general cleanup of test and dot files
2.1.1(trivial) Fixes formatting in README.
2.1.0Fixes parsing error in content-types. Improves behavior of proxyReqBodyDecorator when parseReqBody=false. Repairs issue where authors can't use proxy() twice in Express middleware stack. Fix new Buffer deprecation warning.
2.0.0Update all dependencies; set stage for next iteration. express-http-proxy interface has not changed, but the underlying libraries are not guaranteed to be backward compatible. Versions beyond this point are expected to be run in node verions >= 16.
----------------------------------------------------------------------------
1.6.3[#453] Author should be able to delete headers in userResHeaderDecorator.
1.6.2Update node.js versions used by ci.
1.6.1Minor bug fixes and documentation.
1.6.0Do gzip and gunzip aysyncronously. Test and documentation improvements, dependency updates.
1.5.1Fixes bug in stringifying debug messages.
1.5.0Fixes bug in filter signature. Fix bug in skipToNextHandler, add expressHttpProxy value to user res when skipped. Add tests for host as ip address.
1.4.0DEPRECATED. Critical bug in the filter api.
1.3.0DEPRECATED. Critical bug in the filter api. filter now supports Promises. Update linter to eslint.
1.2.0Auto-stream when no decorations are made to req/res. Improved docs, fixes issues in maybeSkipToNexthandler, allow authors to manage error handling.
1.1.0Add step to allow response headers to be modified.
1.0.7Update dependencies. Improve docs on promise rejection. Fix promise rejection on body limit. Improve debug output.
1.0.6Fixes preserveHostHdr not working, skip userResDecorator on 304, add maybeSkipToNext, test improvements and cleanup.
1.0.5Minor documentation and test patches
1.0.4Minor documentation, test, and package fixes
1.0.3Fixes 'limit option is not taken into account
1.0.2Minor docs corrections.
1.0.1Minor docs adjustments.
1.0.0Major revision.
REMOVE decorateRequest, ADD proxyReqOptDecorator and proxyReqBodyDecorator.
REMOVE intercept, ADD userResDecorator
userResDecorator supports a Promise form for async operations.
General cleanup of structure and application of hooks. Documentation improvements. Update all dependencies. Re-organize code as a series of workflow steps, each (potentially) supporting a promise, and creating a reusable pattern for future development.
0.11.0Allow author to prevent host from being memoized between requests. General program cleanup.
0.10.1Fixed issue where 'body encoding' was being incorrectly set to the character encoding.
Dropped explicit support for node 0.10.
Intercept can now deal with gziped responses.
Author can now 'force https', even if the original request is over http.
Do not call next after ECONNRESET catch.
0.10.0Fix regression in forwardPath implementation.
0.9.1Documentation updates. Set 'Accept-Encoding' header to match bodyEncoding.
0.9.0Better handling for request body when body is JSON.
0.8.0Features: add forwardPathAsync option
Updates: modernize dependencies
Fixes: Exceptions parsing proxied response causes error: Can't set headers after they are sent. (#111)
If client request aborts, proxied request is aborted too (#107)
0.7.4Move jscs to devDependencies to avoid conflict with nsp.
0.7.3Adds a timeout option. Code organization and small bug fixes.
0.7.2Collecting many minor documentation and test improvements.
0.4.0Signature of intercept callback changed from function(data, req, res, callback) to function(rsp, data, req, res, callback) where rsp is the original response from the target

Licence

MIT