Node.js framework agnostic library that enables you to forward an http request to another HTTP server. Supported proxy protocols: HTTP, HTTPS
This library was initially forked from
fast-proxy: https://github.com/fastify/fast-proxy
fast-proxy-lite powers: https://www.npmjs.com/package/fast-gateway 🚀
npm i fast-proxy-lite
The following examples describe how to use fast-proxy-lite with restana:
Gateway:
const { proxy, close } = require('fast-proxy-lite')({
base: 'http://127.0.0.1:3000'
// options
})
const gateway = require('restana')()
gateway.all('/service/*', function (req, res) {
proxy(req, res, req.url, {})
})
gateway.start(8080)Remote service:
const service = require('restana')()
service.get('/service/hi', (req, res) => res.send('Hello World!'))
service.start(3000)Using imports:
import fastProxy from 'fast-proxy-lite'
const { proxy, close } = fastProxy({
base: 'http://127.0.0.1:3000'
})Please see: https://github.com/jkyberneees/nodejs-proxy-benchmarks
Set the base URL for all the forwarded requests.
When
baseis set, requests can only be forwarded to its origin (protocol + host + port). The path ofbaseis not a restriction, see Request target validation.
The number of parsed URLs that will be cached. Default: 100.
Use value =
0to disable the caching mechanism
Allows to optionally overwrite the internal http and https client implementation. Defaults: http and https.
For example, this could be used to add support for following redirects, like so:
...
requests: {
http: require('follow-redirects/http'),
https: require('follow-redirects/https')
}
...Defaults to 1 minute, passed down to [http.Agent][http-agent] and
[https.Agent][https-agent] instances.
Defaults to 2048 sockets, passed down to [http.Agent][http-agent] and
[https.Agent][https-agent] instances.
Defaults to true, passed down to [https.Agent][https-agent] instances.
This needs to be set to false to reply from https servers with
self-signed certificates.
Other supported configurations in https://nodejs.org/api/http.html#http_new_agent_options can also be part of the opts object.
For example, timeout defines the maximum time (in milliseconds) the remote server connection can stay idle while a request is in flight:
const { proxy, close } = require('fast-proxy-lite')({
base: 'http://127.0.0.1:3000',
timeout: 30000
})There is no timeout by default: a remote server that never responds keeps the client request open. Setting
timeouthere, or per request usingopts.request.timeout, is strongly recommended.
Optional "on close resource release" strategy. You can link this to your application shutdown hook as an example.
Enables you to forward an http request to another HTTP server.
proxy(
originReq, // http.IncomingMessage
originRes, // http.ServerResponse
req.url, // String -> remote URL + path or path if base was set
{} // Options described below
)Optionally indicates the base URL for the current request proxy. When used, the global base config is overwriten.
Called when an http response is received from the source.
The default behavior is pump(stream, res), which will be disabled if the
option is specified.
Called when the client HTTP connection to the proxy server unexpectedly terminates before the downstream service response is sent.
// internal implementation
if (!res.socket || res.socket.destroyed || res.writableEnded) {
return onClientConnectionTerminated(res, err, response)
}- The request to the remote server is aborted as soon as the client connection is terminated. In such case
err.codeisECONNRESETandresponseisundefined. - If the remote server responded anyway,
responseis defined anderrisnull. The response stream is destroyed right after the callback returns, unless the callback starts consuming it. - If the client connection was already terminated when
proxywas invoked, nothing is sent to the remote server.
Called to rewrite the headers of the request, before them being sent to the downstream server. It must return the new headers object.
Called to rewrite the headers of the response, before them being copied over to the outer response. It must return the new headers object.
Extended options supported by http[s].request method (https://nodejs.org/api/http.html#http_http_request_options_callback)
The following options are dynamically assigned:
method, port, path, hostname, headers, agent.
Replaces the original querystring of the request with what is specified. Accepts a string or an object.
If
sourcehas no querystring and this option is not set, the querystring of the original request (req.url) is forwarded.
GET and HEAD requests are always forwarded without a payload. For any other method, the payload is taken from req.body when a body parser already consumed the request:
req.body |
Forwarded payload | Default content-type |
|---|---|---|
undefined / null |
the request stream | - |
Stream |
the given stream, using chunked transfer encoding | - |
string |
as is | text/plain |
Buffer / typed array |
as is | application/octet-stream |
object, and the request content-type is application/x-www-form-urlencoded |
URL encoded | application/x-www-form-urlencoded |
| anything else | JSON | application/json |
An empty object (
{}) on a request whose payload was not consumed is considered as "not parsed" (this is whatbody-parserassigns for content types it does not handle), the request stream is forwarded instead.
The content-length/transfer-encoding headers of the forwarded request are always (re)defined by the proxy, they are never copied blindly from the client request:
- A custom
Streamis never framed using thecontent-lengthof the client request, as it does not describe it (e.g: a decompressed payload). If its length is known,rewriteRequestHeaderscan replacetransfer-encodingwithcontent-length. - If
rewriteRequestHeadersreturns both headers,content-lengthis dropped. content-encodingis not forwarded when the payload was decoded by a body parser.
A req.body that can't be serialized (cyclic structures, BigInt values...) is rejected with 400 Bad Request.
- Request: hop-by-hop headers (
connection,keep-alive,proxy-connection,proxy-authorization,te,trailer,transfer-encoding,upgrade,http2-settings) andexpectare not forwarded.hostis set to the remote host, the original value is forwarded asx-forwarded-host. - Response: hop-by-hop headers (
connection,keep-alive,proxy-connection,proxy-authenticate,te,trailer,transfer-encoding,upgrade,http2-settings), the headers nominated by the remoteconnectionheader, andhostare not forwarded.
Protocol upgrades (e.g: WebSockets) are not supported.
The request is rejected with 400 Bad Request, and nothing is sent to the remote server, when:
- The
hostheader is missing. - The method is not upper case. HTTP/2 servers accept
deleteas a method, HTTP clients would send it asDELETE. - The target URL can't be parsed, or its protocol is not
http:orhttps:. baseis set and the target resolves to a different origin.- The target path starts with
//, contains.or..segments (also in their%2eencoded form), backslashes or control characters, or the target starts/ends with a space. URL parsers rewrite those, the path sent to the remote server would be different than the one your router and access control logic have seen (e.g:/public/../adminmatching a/public/*route,//adminnot matching an/adminrule). - The request can't be represented as a valid HTTP request (e.g: invalid header values returned by
rewriteRequestHeaders).
CONNECT requests are rejected with 405 Method Not Allowed.
When
baseis not set,sourcemust be an absolute URL and no origin restriction applies. Never build it from untrusted input.
Anything else is forwarded as received:
/public/..;/admin,/public/..%2fadminor/public//adminare valid paths that reach the remote server untouched. If the remote server applies further normalization (matrix parameters, double decoding, slash merging...), access control has to take it into account.
| Condition | Response |
|---|---|
Remote server refused the connection (ECONNREFUSED) |
503 Service Unavailable |
Remote server timeout or connection reset (ETIMEDOUT, ECONNRESET) |
504 Gateway Timeout |
| Any other failure, including invalid responses | 502 Bad Gateway |
rewriteHeaders, onResponse or onClientConnectionTerminated threw |
500 Internal Server Error |
If the remote server fails after the response headers were sent to the client, the client connection (HTTP/2: the stream) is terminated so the response is not mistaken with a complete one.
Errors thrown by rewriteHeaders, onResponse and onClientConnectionTerminated can't be propagated to the caller, they are reported using process.emitWarning. Errors thrown by rewriteRequestHeaders are propagated to the caller of proxy.
- http-agent: https://nodejs.org/api/http.html#http_new_agent_options
- https-agent: https://nodejs.org/api/https.html#https_class_https_agent
MIT