node-http-proxy
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.
Table of Contents
- Installation
- Upgrading from 0.8.x ?
- Core Concept
- Use Cases
- Options
- Listening for proxy events
- Shutdown
- Miscellaneous
- Contributing and Issues
- License
Installation
npm install http-proxy --save
Upgrading from 0.8.x ?
Click here
Core Concept
A new proxy is created by calling createProxyServer
and passing
an options
object as argument (valid properties are available here)
var httpProxy = ; var proxy = httpProxy; // See (†)
†Unless listen(..) is invoked on the object, this does not create a webserver. See below.
An object will be returned with four methods:
- web
req, res, [options]
(used for proxying regular HTTP(S) requests) - ws
req, socket, head, [options]
(used for proxying WS(S) requests) - listen
port
(a function that wraps the object in a webserver, for your convenience) - close
[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;
Errors can be listened on either using the Event Emitter API
proxy;
or using the callback API
proxy;
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.
Use Cases
Setup a basic stand-alone proxy server
var http = httpProxy = ;//// Create your proxy server and set the target in the options.//httpProxy; // See (†) //// Create your target server//http;
†Invoking listen(..) triggers the creation of a web server. Otherwise, just the proxy instance is created.
Setup a stand-alone proxy server with custom server logic
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 = httpProxy = ; //// Create a proxy server with custom application logic//var proxy = httpProxy; //// 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; consoleserver;
Setup a stand-alone proxy server with proxy request header re-writing
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 = httpProxy = ; //// Create a proxy server with custom application logic//var proxy = httpProxy; // 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; var server = http; consoleserver;
Modify a response from a proxied server
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.
Setup a stand-alone proxy server with latency
var http = httpProxy = ; //// Create a proxy server with latency//var proxy = httpProxy; //// Create your server that makes an operation that waits a while// and then proxies the request//http; //// Create your target server//http;
Using HTTPS
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.
HTTPS -> HTTP
//// Create the HTTPS proxy server in front of a HTTP server//httpProxy;
HTTPS -> HTTPS
//// Create the proxy server listening on port 443//httpProxy;
Proxying WebSockets
You can activate the websocket support for the proxy using ws:true
in the options.
//// Create a proxy server for websockets//httpProxy;
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 = target: host: 'localhost' port: 9015 ;var proxyServer = http; //// Listen to the `upgrade` event and proxy the// WebSocket requests as well.//proxyServer; proxyServer;
Options
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 rewriting- String: new domain, for example
cookieDomainRewrite: "new.domain"
. To remove the domain, usecookieDomainRewrite: ""
. - Object: mapping of domains to new domains, use
"*"
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", "*": "" }
- headers: object with extra headers to be added to target requests.
- proxyTimeout: timeout (in millis) when proxy receives no response from target
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:
- ssl: object to be passed to https.createServer()
- ws: true/false, if you want to proxy websockets
Listening for proxy events
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.- (DEPRECATED)
proxySocket
: Deprecated in favor ofopen
.
var httpProxy = ;// Error example//// Http Proxy Server with bad target//var proxy = httpProxy; proxy; //// Listen for the `error` event on `proxy`.proxy; //// Listen for the `proxyRes` event on `proxy`.//proxy; //// Listen for the `open` event on `proxy`.//proxy; //// Listen for the `close` event on `proxy`.//proxy;
Shutdown
- When testing or running server within another program it may be necessary to close the proxy.
- This will stop the proxy from accepting new connections.
var proxy = target: host: 'localhost' port: 1337 ; proxy;
Miscellaneous
ProxyTable API
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.
Test
$ npm test
Logo
Logo created by Diego Pasquali
Contributing and Issues
- Search on Google/Github
- If you can't find anything, open an issue
- If you feel comfortable about fixing the issue, fork the repo
- Commit to your local branch (which must be different from
master
) - Submit your Pull Request (be sure to include tests and update documentation)
License
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.