Gathering detailed insights and metrics for koa-http2-proxy2
Gathering detailed insights and metrics for koa-http2-proxy2
Gathering detailed insights and metrics for koa-http2-proxy2
Gathering detailed insights and metrics for koa-http2-proxy2
⚡ The one-liner node.js http2-proxy middleware for koa
npm install koa-http2-proxy2
Typescript
Module System
Min. Node Version
Node Version
NPM Version
TypeScript (99.92%)
JavaScript (0.08%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
NOASSERTION License
1 Stars
240 Commits
2 Branches
1 Contributors
Updated on Aug 04, 2023
Latest Version
0.0.8
Package Id
koa-http2-proxy2@0.0.8
Unpacked Size
45.62 kB
Size
13.60 kB
File Count
12
NPM Version
8.5.0
Node Version
16.14.2
Published on
Jun 01, 2023
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
forked from ontola/koa-http2-proxy. On its basis, the following problems are solved 👇
Proxy requests to http://www.example.org
1var Koa = require('koa'); 2var proxy = require('koa-http2-proxy2'); 3var app = new Koa(); 4 5// response 6app.use(proxy({ target: 'http://www.example.org' })); 7 8app.listen(3000); 9 10// http://localhost:3000/foo/bar -> http://www.example.org/foo/bar
:bulb: Tip: Set the option changeOrigin
to true
for name-based virtual hosted sites.
1$ npm install --save-dev koa-http2-proxy2
Proxy middleware configuration.
1var proxy = require('koa-http2-proxy2'); 2 3var apiProxy = proxy('/api', { target: 'http://www.example.org' }); 4// \____/ \_____________________________/ 5// | | 6// context options 7 8// 'apiProxy' is now ready to be used as middleware in a server.
(full list of koa-http2-proxy2
configuration options)
1// shorthand syntax for the example above: 2var apiProxy = proxy('http://www.example.org/api');
More about the shorthand configuration.
1// include dependencies 2var Koa = require('koa'); 3var proxy = require('koa-http2-proxy2'); 4 5// proxy middleware options 6var options = { 7 target: 'http://www.example.org', // target host 8 ws: true, // proxy websockets 9 pathRewrite: { 10 '^/api/old-path': '/api/new-path', // rewrite path 11 '^/api/remove/path': '/path' // remove base path 12 }, 13 router: { 14 // when request.headers.host == 'dev.localhost:3000', 15 // override target 'http://www.example.org' to 'http://localhost:8000' 16 'dev.localhost:3000': 'http://localhost:8000' 17 } 18}; 19 20// create the proxy (without context) 21var exampleProxy = proxy(options); 22 23// mount `exampleProxy` in web server 24var app = new Koa(); 25app.use(exampleProxy); 26app.listen(3000);
Providing an alternative way to decide which requests should be proxied; In case you are not able to use the server's path
parameter to mount the proxy or when you need more flexibility.
RFC 3986 path
is used for context matching.
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
path matching
proxy({...})
- matches any path, all requests will be proxied.proxy('/', {...})
- matches any path, all requests will be proxied.proxy('/api', {...})
- matches paths starting with /api
proxy(/^\/([a-zA-Z0-9_/-]{1,})$/, {...})
- matches paths with regexpmultiple path matching
proxy(['/api', '/ajax', '/someotherpath'], {...})
wildcard path matching
For fine-grained control you can use wildcard matching. Glob pattern matching is done by micromatch. Visit micromatch or glob for more globbing examples.
proxy('**', {...})
matches any path, all requests will be proxied.proxy('**/*.html', {...})
matches any path which ends with .html
proxy('/*.html', {...})
matches paths directly under path-absoluteproxy('/api/**/*.html', {...})
matches requests ending with .html
in the path of /api
proxy(['/api/**', '/ajax/**'], {...})
combine multiple patternsproxy(['/api/**', '!**/bad.json'], {...})
exclusionNote: In multiple path matching, you cannot use string paths and wildcard paths together.
custom matching
For full control you can provide a custom function to determine which requests should be proxied or not.
1/** 2 * @return {Boolean} 3 */ 4var filter = function(pathname, req) { 5 return pathname.match('^/api') && req.method === 'GET'; 6}; 7 8var apiProxy = proxy(filter, { target: 'http://www.example.org' });
option.pathRewrite: object/function, rewrite target's url path. Object-keys will be used as RegExp to match paths.
1// rewrite path 2pathRewrite: {'^/old/api' : '/new/api'} 3 4// remove path 5pathRewrite: {'^/remove/api' : ''} 6 7// add base path 8pathRewrite: {'^/' : '/basepath/'} 9 10// custom rewriting 11pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }
option.router: object/function, re-target option.target
for specific requests.
1// Use `host` and/or `path` to match requests. First match will be used. 2// The order of the configuration matters. 3router: { 4 'integration.localhost:3000' : 'http://localhost:8001', // host only 5 'staging.localhost:3000' : 'http://localhost:8002', // host only 6 'localhost:3000/api' : 'http://localhost:8003', // host + path 7 '/rest' : 'http://localhost:8004' // path only 8} 9 10// Custom router function 11router: function(req) { 12 return 'http://localhost:8004'; 13}
option.logLevel: string, ['debug', 'info', 'warn', 'error', 'silent']. Default: 'info'
option.logProvider: function, modify or replace log provider. Default: console
.
1// simple replace 2function logProvider(provider) { 3 // replace the default console log provider. 4 return require('winston'); 5}
1// verbose replacement 2function logProvider(provider) { 3 var logger = new (require('winston')).Logger(); 4 5 var myCustomProvider = { 6 log: logger.log, 7 debug: logger.debug, 8 info: logger.info, 9 warn: logger.warn, 10 error: logger.error 11 }; 12 return myCustomProvider; 13}
option.onError: function, subscribe to http-proxy's error
event for custom error handling.
1function onError(err, ctx) { 2 ctx.response.status = 500; 3 ctx.response.body = 4 'Something went wrong. And we are reporting a custom error message.'; 5}
option.onProxyRes: function, subscribe to http-proxy's proxyRes
event.
1function onProxyRes(proxyRes, ctx) { 2 proxyRes.headers['x-added'] = 'foobar'; // add new header to response 3 delete proxyRes.headers['x-removed']; // remove header from response 4}
option.onProxyReq: function, subscribe to http-proxy's proxyReq
event.
1function onProxyReq(proxyReq, ctx) { 2 // add custom header to request 3 proxyReq.setHeader('x-added', 'foobar'); 4 // or log the req 5}
option.onUpgrade: function, called before upgrading a websocket connection.
1onUpgrade: async ctx => { 2 // add session middleware to the websocket connection 3 // see option.app 4 await session(ctx, () => {}); 5};
option.app: koa app, used to generate a koa ctx to be used in onUpgrade. If left blank, a object containing only req
will be used as context
option.headers: object, adds request headers. (Example: {host:'www.example.org'}
)
option.target: url string to be parsed with the url module
option.ws: true/false: if you want to proxy websockets
option.xfwd: true/false, adds x-forward headers
option.changeOrigin: true/false, Default: false - changes the origin of the host header to the target URL
option.proxyTimeout: timeout (in millis) when proxy receives no response from target
option.proxyName: Proxy name used for Via header
option.logs: true/false: Whether to enable log printing, default false
Use the shorthand syntax when verbose configuration is not needed. The context
and option.target
will be automatically configured when shorthand is used. Options can still be used if needed.
1proxy('http://www.example.org:8000/api'); 2// proxy('/api', {target: 'http://www.example.org:8000'}); 3 4proxy('http://www.example.org:8000/api/books/*/**.json'); 5// proxy('/api/books/*/**.json', {target: 'http://www.example.org:8000'}); 6 7proxy('http://www.example.org:8000/api'); 8// proxy('/api', {target: 'http://www.example.org:8000'});
1// verbose api 2proxy('/', { target: 'http://echo.websocket.org', ws: true }); 3 4// shorthand 5proxy('http://echo.websocket.org', { ws: true }); 6 7// shorter shorthand 8proxy('ws://echo.websocket.org');
In the previous WebSocket examples, http-proxy-middleware relies on a initial http request in order to listen to the http upgrade
event. If you need to proxy WebSockets without the initial http request, you can subscribe to the server's http upgrade
event manually.
1var wsProxy = proxy('ws://echo.websocket.org'); 2 3var app = new Koa(); 4app.use(wsProxy); 5 6var server = app.listen(3000); 7server.on('upgrade', wsProxy.upgrade); // <-- subscribe to http 'upgrade'
Run the test suite:
1# install dependencies 2$ yarn 3 4# linting 5$ yarn lint 6$ yarn lint:fix 7 8# building (compile typescript to js) 9$ yarn build 10 11# unit tests 12$ yarn test 13 14# code coverage 15$ yarn cover
The MIT License (MIT)
Copyright for portions of this project are held by Steven Chim, 2015-2019 as part of http-proxy-middleware. All other copyright for this project are held by Ontola BV, 2019.
No vulnerabilities found.
No security vulnerabilities found.