A simple http/2 & http/1.1 to http/1.1 spec compliant proxy helper for Node.
- Proxies HTTP 2, HTTP 1 and WebSocket
- Simple and high performance
- Hop by hop header handling.
- Connection header handling
- Via header handling
- Forwarded header handling
$ npm install http2-proxy
http2-proxy
requires at least node v8.7.0.
You must pass allowHTTP1: true
to the http2.createServer
or http2.createSecureServer
factory methods.
import http2 from 'http2'
import proxy from 'http2-proxy'
const server = http2.createServer({ allowHTTP1: true })
server.listen(8000)
You can also use http-proxy2
with the old http
&& https
API's.
import http from 'http'
const server = http.createServer()
server.listen(8000)
server.on('request', (req, res) => {
proxy.web(req, res, {
hostname: 'localhost'
port: 9000
}, err => {
if (err) {
console.error('proxy error', err)
}
})
})
server.on('upgrade', (req, socket, head) => {
proxy.ws(req, socket, head, {
hostname: 'localhost'
port: 9000
}, err => {
if (err) {
console.error('proxy error', err)
}
})
})
Use Helmet to secure response headers
server.on('request', (req, res) => {
proxy.web(req, res, {
hostname: 'localhost'
port: 9000,
onRes: (req, res) => helmet(req, res, () => {})
}, err => {
if (err) {
console.error('proxy error', err)
}
})
})
server.on('request', (req, res) => {
proxy.web(req, res, {
hostname: 'localhost'
port: 9000,
onReq: (req, { headers }) => {
headers['x-forwarded-for'] = req.socket.remoteAddress
headers['x-forwarded-proto'] = req.socket.encrypted ? 'https' : 'http'
headers['x-forwarded-host'] = req.headers['host']
}
}, err => {
if (err) {
console.error('proxy error', err)
}
})
})
const http = require('follow-redirects').http
server.on('request', (req, res) => {
proxy.web(req, res, {
hostname: 'localhost'
port: 9000,
onReq: (req, options) => http.request(options)
}, err => {
if (err) {
console.error('proxy error', err)
}
})
})
req
:http.IncomingMessage
orhttp2.Http2ServerRequest
res
:http.ServerResponse
orhttp2.Http2ServerResponse
options
: See Optionscallback(err)
: Called on completion or error. Optional
Returns a promise if no callback is provided.
See request
req
:http.IncomingMessage
socket
:net.Socket
head
:Buffer
options
: See Optionscallback(err)
: Called on completion or error. Optional
Returns a promise if no callback is provided.
See upgrade
hostname
: Proxyhttp.request(options)
target hostnameport
: Proxyhttp.request(options)
target portproxyTimeout
: Proxyhttp.request(options)
timeoutproxyName
: Proxy name used for Via headertimeout
:http.IncomingMessage
orhttp2.Http2ServerRequest
timeoutonReq(req, options)
: Called before proxy request. If returning a truthy value it will be used as the request.req
:http.IncomingMessage
orhttp2.Http2ServerRequest
options
: Options passed tohttp.request(options)
onRes(req, resOrSocket)
: Called before proxy responsereq
:http.IncomingMessage
orhttp2.Http2ServerRequest
resOrSocket
: Forweb
http.ServerResponse
orhttp2.Http2ServerResponse
and forws
net.Socket