5 つのパッケージは、HTTP トラフィックの転送や仲介を行うためのツールですが、目的が大きく 2 つに分かれます。http-proxy、http-proxy-middleware、express-http-proxy、proxy-middleware は、主に受信リクエストを別のサーバーに転送する「リバースプロキシ」として機能します。一方、http-proxy-agent は、アプリケーションから外部 API へ送信するリクエストを、企業プロキシなど経由させるための「アウトバウンドトンネリング」に使用されます。開発環境の API プロキシ設定や、本番環境でのトラフィック制御を行う際には、前者のグループから選択します。社内のネットワーク制約により外部通信にプロキシが必要な場合は、後者の http-proxy-agent が必要になります。
Node.js エコシステムには、HTTP リクエストを中継するためのパッケージが多数存在します。しかし、名前が似ていても目的が全く異なるケースがあり、誤った選択をするとセキュリティ問題や接続エラーの原因になります。ここでは、express-http-proxy、http-proxy、http-proxy-agent、http-proxy-middleware、proxy-middleware の 5 つを比較し、実際の開発現場でどのように使い分けるべきかを解説します。
まず最も重要な点として、http-proxy-agent は他の 4 つとは根本的に役割が異なります。
http-proxy、http-proxy-middleware など):クライアントから届いたリクエストを、別のサーバーに転送します。開発サーバーで API リクエストをバックエンドに流す際などに使います。http-proxy-agent):自分のアプリから外部へリクエストを送る際、経由するプロキシサーバーを指定します。企業ネットワーク内で外部 API にアクセスする際などに使います。この違いを理解せずに http-proxy-agent を Express のミドルウェアとして使おうとすると、動作しません。逆に、開発サーバーのプロキシ設定に http-proxy-agent を使っても目的は達成できません。
Express や Connect を使っている場合、主に http-proxy-middleware、express-http-proxy、proxy-middleware のいずれかを選ぶことになります。http-proxy はこれらの基盤となるライブラリです。
http-proxy-middleware:現代の標準現在、Express アプリでプロキシを設定する際のデファクトスタンダードです。設定が柔軟で、メンテナンスも活発です。
// http-proxy-middleware の使用例
const { createProxyMiddleware } = require('http-proxy-middleware');
app.use('/api', createProxyMiddleware({
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: { '^/api': '' }
}));
express-http-proxy:Express 特化型Express 向けに設計されており、API がシンプルです。複雑な設定が必要ない場合に適しています。
// express-http-proxy の使用例
const proxy = require('express-http-proxy');
app.use('/api', proxy('http://localhost:3000', {
proxyReqPathResolver: (req) => {
return req.url.replace('/api', '');
}
}));
http-proxy:低レベルな制御フレームワークに依存しない純粋なプロキシサーバーです。Express 以外のカスタム HTTP サーバーを書く場合に使います。
// http-proxy の使用例
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
app.use((req, res) => {
proxy.web(req, res, { target: 'http://localhost:3000' });
});
proxy-middleware:レガシーな選択肢かつては広く使われていましたが、現在はメンテナンスが停滞しており、新規プロジェクトでの使用は推奨されません。
// proxy-middleware の使用例(非推奨)
const proxy = require('proxy-middleware');
app.use('/api', proxy('http://localhost:3000'));
http-proxy-agentこのパッケージは、Node.js の http モジュールや fetch などで、外部プロキシを経由して通信したい場合に使用します。
// http-proxy-agent の使用例
const { HttpProxyAgent } = require('http-proxy-agent');
const http = require('http');
const agent = new HttpProxyAgent('http://proxy.example.com:8080');
http.get('http://example.com', { agent }, (res) => {
// プロキシ経由でレスポンスを受け取る
});
パッケージの選定において、メンテナンス状況は重要な判断材料です。
proxy-middleware:多くのバージョンが長期間更新されておらず、セキュリティ修正も遅れがちです。既存のプロジェクトにある場合は、http-proxy-middleware への移行を検討すべきです。express-http-proxy:メンテナンスは続いています。ただし、機能の豊富さでは http-proxy-middleware に劣る場合があります。http-proxy-middleware:定期的に更新されており、コミュニティでのサポートも厚いです。http-proxy:コアライブラリとして安定しています。http-proxy-agent:外部プロキシ経由通信の標準として安定しています。| 特徴 | http-proxy-middleware | express-http-proxy | http-proxy | proxy-middleware | http-proxy-agent |
|---|---|---|---|---|---|
| 主な用途 | 受信リクエスト転送 | 受信リクエスト転送 | 受信リクエスト転送 | 受信リクエスト転送 | 送信リクエスト経路 |
| Express 対応 | ✅ 最適化済み | ✅ 特化 | ⚠️ 手動設定必要 | ✅ 対応 | ❌ 非対応 |
| 設定の柔軟性 | 高い | 普通 | 非常に高い | 低い | 経路設定のみ |
| メンテナンス | 活発 | 継続中 | 安定 | 停滞(非推奨) | 安定 |
| 推奨度 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐ | ⭐⭐⭐⭐⭐(用途限定) |
実際のプロジェクトでは、以下の基準で選択すると失敗がありません。
Express アプリで API プロキシを設定したい
http-proxy-middleware を選択してください。ドキュメントが豊富で、トラブル時の情報も入手しやすいです。Express 以外のカスタムサーバーを書いている
http-proxy を直接使用します。ミドルウェアレイヤーがないため、自分でリクエストハンドリングを書く必要があります。企業ネットワーク内で外部 API を叩く必要がある
http-proxy-agent を使用します。これはミドルウェアではなく、HTTP クライアントのオプションとして設定します。既存の古いプロジェクトを保守している
proxy-middleware や express-http-proxy が使われている場合、すぐに壊れていなければ無理に変える必要はありません。ただし、新規機能追加時には http-proxy-middleware への移行計画を立てましょう。名前が似ているパッケージでも、役割は「受信転送」か「送信経路」かで全く異なります。まずこの点を明確にし、その上で Express を使っているなら http-proxy-middleware、それ以外の特殊な要件に応じて他を選ぶのが賢明です。特に proxy-middleware は技術的負債になりやすいため、新規採用は避けるべきでしょう。
Express や Connect に依存しない、純粋な Node.js HTTP サーバーを構築する場合に選択します。最も低レベルな制御が可能ですが、ミドルウェアとしての設定は自分で実装する必要があります。
Express アプリでシンプルにプロキシを設定したい場合に選択します。設定項目が少なく、直感的な API が特徴ですが、複雑なルート制御には向いていません。
アプリケーションから外部 API へ通信する際、企業ファイアウォールやプロキシサーバーを経由する必要がある場合に選択します。受信リクエストの処理ではなく、送信リクエストの経路制御に使用します。
Express や Connect アプリで、柔軟かつ標準的なプロキシ設定を行いたい場合に選択します。現在最も広く採用されており、メンテナンス性や機能面でバランスが取れています。
過去の資産で既に導入されている場合を除き、新規プロジェクトでの使用は避けるべきです。メンテナンス頻度が低く、現代の Express の仕組みとの相性が良くありません。
node-http-proxy is an HTTP programmable proxying library that supports
websockets. It is suitable for implementing components such as reverse
proxies and load balancers.
npm install http-proxy --save
Click here
A new proxy is created by calling createProxyServer and passing
an options object as argument (valid properties are available here)
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer(options); // See (†)
†Unless listen(..) is invoked on the object, this does not create a webserver. See below.
An object will be returned with four methods:
req, res, [options] (used for proxying regular HTTP(S) requests)req, socket, head, [options] (used for proxying WS(S) requests)port (a function that wraps the object in a webserver, for your convenience)[callback] (a function that closes the inner webserver and stops listening on given port)It is then possible to proxy requests by calling these functions
http.createServer(function(req, res) {
proxy.web(req, res, { target: 'http://mytarget.com:8080' });
});
Errors can be listened on either using the Event Emitter API
proxy.on('error', function(e) {
...
});
or using the callback API
proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... });
When a request is proxied it follows two different pipelines (available here)
which apply transformations to both the req and res object.
The first pipeline (incoming) is responsible for the creation and manipulation of the stream that connects your client to the target.
The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data
to the client.
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create your proxy server and set the target in the options.
//
httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000); // See (†)
//
// Create your target server
//
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
†Invoking listen(..) triggers the creation of a web server. Otherwise, just the proxy instance is created.
This example shows how you can proxy a request using your own HTTP server and also you can put your own logic to handle the request.
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});
//
// Create your custom server and just call `proxy.web()` to proxy
// a web request to the target passed in the options
// also you can use `proxy.ws()` to proxy a websockets request
//
var server = http.createServer(function(req, res) {
// You can define here your custom logic to handle the request
// and then proxy the request.
proxy.web(req, res, { target: 'http://127.0.0.1:5050' });
});
console.log("listening on port 5050")
server.listen(5050);
This example shows how you can proxy a request using your own HTTP server that modifies the outgoing proxy request by adding a special header.
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});
// To modify the proxy connection before data is sent, you can listen
// for the 'proxyReq' event. When the event is fired, you will receive
// the following arguments:
// (http.ClientRequest proxyReq, http.IncomingMessage req,
// http.ServerResponse res, Object options). This mechanism is useful when
// you need to modify the proxy request before the proxy connection
// is made to the target.
//
proxy.on('proxyReq', function(proxyReq, req, res, options) {
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
});
var server = http.createServer(function(req, res) {
// You can define here your custom logic to handle the request
// and then proxy the request.
proxy.web(req, res, {
target: 'http://127.0.0.1:5050'
});
});
console.log("listening on port 5050")
server.listen(5050);
Sometimes when you have received a HTML/XML document from the server of origin you would like to modify it before forwarding it on.
Harmon allows you to do this in a streaming style so as to keep the pressure on the proxy to a minimum.
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create a proxy server with latency
//
var proxy = httpProxy.createProxyServer();
//
// Create your server that makes an operation that waits a while
// and then proxies the request
//
http.createServer(function (req, res) {
// This simulates an operation that takes 500ms to execute
setTimeout(function () {
proxy.web(req, res, {
target: 'http://localhost:9008'
});
}, 500);
}).listen(8008);
//
// Create your target server
//
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9008);
You can activate the validation of a secure SSL certificate to the target connection (avoid self-signed certs), just set secure: true in the options.
//
// Create the HTTPS proxy server in front of a HTTP server
//
httpProxy.createServer({
target: {
host: 'localhost',
port: 9009
},
ssl: {
key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
}
}).listen(8009);
//
// Create the proxy server listening on port 443
//
httpProxy.createServer({
ssl: {
key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
},
target: 'https://localhost:9010',
secure: true // Depends on your needs, could be false.
}).listen(443);
//
// Create an HTTP proxy server with an HTTPS target
//
httpProxy.createProxyServer({
target: {
protocol: 'https:',
host: 'my-domain-name',
port: 443,
pfx: fs.readFileSync('path/to/certificate.p12'),
passphrase: 'password',
},
changeOrigin: true,
}).listen(8000);
You can activate the websocket support for the proxy using ws:true in the options.
//
// Create a proxy server for websockets
//
httpProxy.createServer({
target: 'ws://localhost:9014',
ws: true
}).listen(8014);
Also you can proxy the websocket requests just calling the ws(req, socket, head) method.
//
// Setup our server to proxy standard HTTP requests
//
var proxy = new httpProxy.createProxyServer({
target: {
host: 'localhost',
port: 9015
}
});
var proxyServer = http.createServer(function (req, res) {
proxy.web(req, res);
});
//
// Listen to the `upgrade` event and proxy the
// WebSocket requests as well.
//
proxyServer.on('upgrade', function (req, socket, head) {
proxy.ws(req, socket, head);
});
proxyServer.listen(8015);
httpProxy.createProxyServer supports the following options:
target: url string to be parsed with the url module
forward: url string to be parsed with the url module
agent: object to be passed to http(s).request (see Node's https agent and http agent objects)
ssl: object to be passed to https.createServer()
ws: true/false, if you want to proxy websockets
xfwd: true/false, adds x-forward headers
secure: true/false, if you want to verify the SSL Certs
toProxy: true/false, passes the absolute URL as the path (useful for proxying to proxies)
prependPath: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path
ignorePath: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required).
localAddress: Local interface string to bind for outgoing connections
changeOrigin: true/false, Default: false - changes the origin of the host header to the target URL
preserveHeaderKeyCase: true/false, Default: false - specify whether you want to keep letter case of response header key
auth: Basic authentication i.e. 'user:password' to compute an Authorization header.
hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects.
autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
cookieDomainRewrite: rewrites domain of set-cookie headers. Possible values:
false (default): disable cookie rewritingcookieDomainRewrite: "new.domain". To remove the domain, use cookieDomainRewrite: ""."*" to match all domains.
For example keep one domain unchanged, rewrite one domain and remove other domains:
cookieDomainRewrite: {
"unchanged.domain": "unchanged.domain",
"old.domain": "new.domain",
"*": ""
}
cookiePathRewrite: rewrites path of set-cookie headers. Possible values:
false (default): disable cookie rewritingcookiePathRewrite: "/newPath/". To remove the path, use cookiePathRewrite: "". To set path to root use cookiePathRewrite: "/"."*" to match all paths.
For example, to keep one path unchanged, rewrite one path and remove other paths:
cookiePathRewrite: {
"/unchanged.path/": "/unchanged.path/",
"/old.path/": "/new.path/",
"*": ""
}
headers: object with extra headers to be added to target requests.
proxyTimeout: timeout (in millis) for outgoing proxy requests
timeout: timeout (in millis) for incoming requests
followRedirects: true/false, Default: false - specify whether you want to follow redirects
selfHandleResponse true/false, if set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event
buffer: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e.g. If you read the body of a request into a field called 'req.rawbody' you could restream this field in the buffer option:
'use strict';
const streamify = require('stream-array');
const HttpProxy = require('http-proxy');
const proxy = new HttpProxy();
module.exports = (req, res, next) => {
proxy.web(req, res, {
target: 'http://localhost:4003/',
buffer: streamify(req.rawBody)
}, next);
};
NOTE:
options.ws and options.ssl are optional.
options.target and options.forward cannot both be missing
If you are using the proxyServer.listen method, the following options are also applicable:
error: The error event is emitted if the request to the target fail. We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.proxyReq: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "web" connectionsproxyReqWs: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "websocket" connectionsproxyRes: This event is emitted if the request to the target got a response.open: This event is emitted once the proxy websocket was created and piped into the target websocket.close: This event is emitted once the proxy websocket was closed.proxySocket: Deprecated in favor of open.var httpProxy = require('http-proxy');
// Error example
//
// Http Proxy Server with bad target
//
var proxy = httpProxy.createServer({
target:'http://localhost:9005'
});
proxy.listen(8005);
//
// Listen for the `error` event on `proxy`.
proxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.');
});
//
// Listen for the `proxyRes` event on `proxy`.
//
proxy.on('proxyRes', function (proxyRes, req, res) {
console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});
//
// Listen for the `open` event on `proxy`.
//
proxy.on('open', function (proxySocket) {
// listen for messages coming FROM the target here
proxySocket.on('data', hybiParseAndLogMessage);
});
//
// Listen for the `close` event on `proxy`.
//
proxy.on('close', function (res, socket, head) {
// view disconnected websocket connections
console.log('Client disconnected');
});
var proxy = new httpProxy.createProxyServer({
target: {
host: 'localhost',
port: 1337
}
});
proxy.close();
If you want to handle your own response after receiving the proxyRes, you can do
so with selfHandleResponse. As you can see below, if you use this option, you
are able to intercept and read the proxyRes but you must also make sure to
reply to the res itself otherwise the original client will never receive any
data.
var option = {
target: target,
selfHandleResponse : true
};
proxy.on('proxyRes', function (proxyRes, req, res) {
var body = [];
proxyRes.on('data', function (chunk) {
body.push(chunk);
});
proxyRes.on('end', function () {
body = Buffer.concat(body).toString();
console.log("res from proxied server:", body);
res.end("my response to cli");
});
});
proxy.web(req, res, option);
A proxy table API is available through this add-on module, which lets you define a set of rules to translate matching routes to target routes that the reverse proxy will talk to.
$ npm test
Logo created by Diego Pasquali
master)The MIT License (MIT)
Copyright (c) 2010 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.