Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
http-proxy
Advanced tools
The http-proxy npm package is a full-featured HTTP proxy library for Node.js. It supports websockets and can be used to proxy different kinds of HTTP and HTTPS traffic, which makes it suitable for implementing reverse proxies and load balancers.
Proxying HTTP/HTTPS requests
This code creates an HTTP server that listens on port 8000 and proxies all incoming requests to 'http://mytarget.com:8080'.
const http = require('http');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
const server = http.createServer(function(req, res) {
proxy.web(req, res, { target: 'http://mytarget.com:8080' });
});
server.listen(8000);
Proxying WebSockets
This code sets up a server that can proxy WebSocket connections to 'ws://mytarget.com:8080' when an 'upgrade' event is emitted.
const http = require('http');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
const server = http.createServer(function(req, res) {
// This function is not used when proxying WebSockets
});
server.on('upgrade', function(req, socket, head) {
proxy.ws(req, socket, head, { target: 'ws://mytarget.com:8080' });
});
server.listen(8000);
Listening for proxy events
This code listens for errors and responses from the proxy server, allowing for custom error handling and logging.
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
proxy.on('error', function(err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong.');
});
proxy.on('proxyRes', function(proxyRes, req, res) {
console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});
node-http-proxy is a similar package that offers high-performance reverse proxy and load balancing capabilities. It is often compared to http-proxy due to its similar feature set.
Redbird is a modern reverse proxy library for node that includes automatic HTTPS, WebSocket support, and Docker integration. It is an alternative to http-proxy with a focus on simplicity and ease of use.
Bouncy is a simple module for writing WebSocket and regular HTTP servers. It allows you to route requests to different destinations based on the request headers or other properties. It is less feature-rich compared to http-proxy but can be used for simpler proxying needs.
node-http-proxy
is an HTTP programmable proxying library that supports
websockets. It is suitable for implementing components such as
proxies and load balancers.
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);
An object will be returned with four values:
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 (ingoing) 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);
//
// 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);
This example show 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:5060' });
});
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:5060'
});
});
console.log("listening on port 5050")
server.listen(5050);
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create a proxy server with latency
//
var proxy = httpProxy.createProxyServer();
//
// Create your server that make an operation that take a while
// and then proxy de request
//
http.createServer(function (req, res) {
// This simulate an operation that take 500ms in 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);
error
: The error event is emitted if the request to the target fail.proxyRes
: This event is emitted if the request to the target got a response.proxySocket
: This event is emitted once the proxy websocket was created and piped into the target websocket.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 `proxySocket` event on `proxy`.
//
proxy.on('proxySocket', function (proxySocket) {
// listen for messages coming FROM the target here
proxySocket.on('data', hybiParseAndLogMessage);
});
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);
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);
master
)httpProxy.createProxyServer
supports the following options:
path
(useful for proxying to proxies)If you are using the proxyServer.listen
method, the following options are also applicable:
var proxy = new httpProxy.createProxyServer({
target: {
host: 'localhost',
port: 1337
}
});
proxy.close();
$ npm test
Logo created by Diego Pasquali
The MIT License (MIT)
Copyright (c) 2010 - 2013 Nodejitsu Inc.
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.
FAQs
HTTP proxying for the masses
The npm package http-proxy receives a total of 8,812,274 weekly downloads. As such, http-proxy popularity was classified as popular.
We found that http-proxy demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.