UNPKG

20.3 kBMarkdownView Raw
1# http-proxy-middleware
2
3[![Build Status](https://img.shields.io/travis/chimurai/http-proxy-middleware/master.svg?style=flat-square)](https://travis-ci.org/chimurai/http-proxy-middleware)
4[![Coveralls](https://img.shields.io/coveralls/chimurai/http-proxy-middleware.svg?style=flat-square)](https://coveralls.io/r/chimurai/http-proxy-middleware)
5[![dependency Status](https://img.shields.io/david/chimurai/http-proxy-middleware.svg?style=flat-square)](https://david-dm.org/chimurai/http-proxy-middleware#info=dependencies)
6[![dependency Status](https://snyk.io/test/npm/http-proxy-middleware/badge.svg?style=flat-square)](https://snyk.io/test/npm/http-proxy-middleware)
7[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
8
9Node.js proxying made simple. Configure proxy middleware with ease for [connect](https://github.com/senchalabs/connect), [express](https://github.com/strongloop/express), [browser-sync](https://github.com/BrowserSync/browser-sync) and [many more](#compatible-servers).
10
11Powered by the popular Nodejitsu [`http-proxy`](https://github.com/nodejitsu/node-http-proxy). [![GitHub stars](https://img.shields.io/github/stars/nodejitsu/node-http-proxy.svg?style=social&label=Star)](https://github.com/nodejitsu/node-http-proxy)
12
13## ⚠️ Note
14
15This page is showing documentation for version v1.x.x ([release notes](https://github.com/chimurai/http-proxy-middleware/releases))
16
17If you're looking for v0.x documentation. Go to:
18https://github.com/chimurai/http-proxy-middleware/tree/v0.21.0#readme
19
20## TL;DR
21
22Proxy `/api` requests to `http://www.example.org`
23
24```javascript
25// javascript
26
27const express = require('express');
28const { createProxyMiddleware } = require('http-proxy-middleware');
29
30const app = express();
31
32app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));
33app.listen(3000);
34
35// http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar
36```
37
38```typescript
39// typescript
40
41import * as express from 'express';
42import { createProxyMiddleware, Filter, Options, RequestHandler } from 'http-proxy-middleware';
43
44const app = express();
45
46app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));
47app.listen(3000);
48
49// http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar
50```
51
52_All_ `http-proxy` [options](https://github.com/nodejitsu/node-http-proxy#options) can be used, along with some extra `http-proxy-middleware` [options](#options).
53
54:bulb: **Tip:** Set the option `changeOrigin` to `true` for [name-based virtual hosted sites](http://en.wikipedia.org/wiki/Virtual_hosting#Name-based).
55
56## Table of Contents
57
58<!-- MarkdownTOC autolink=true bracket=round depth=2 -->
59
60- [Install](#install)
61- [Core concept](#core-concept)
62- [Example](#example)
63- [Context matching](#context-matching)
64- [Options](#options)
65 - [http-proxy-middleware options](#http-proxy-middleware-options)
66 - [http-proxy events](#http-proxy-events)
67 - [http-proxy options](#http-proxy-options)
68- [Shorthand](#shorthand)
69 - [app.use\(path, proxy\)](#appusepath-proxy)
70- [WebSocket](#websocket)
71 - [External WebSocket upgrade](#external-websocket-upgrade)
72- [Working examples](#working-examples)
73- [Recipes](#recipes)
74- [Compatible servers](#compatible-servers)
75- [Tests](#tests)
76- [Changelog](#changelog)
77- [License](#license)
78
79<!-- /MarkdownTOC -->
80
81## Install
82
83```bash
84$ npm install --save-dev http-proxy-middleware
85```
86
87## Core concept
88
89Proxy middleware configuration.
90
91#### createProxyMiddleware([context,] config)
92
93```javascript
94const { createProxyMiddleware } = require('http-proxy-middleware');
95
96const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org' });
97// \____/ \_____________________________/
98// | |
99// context options
100
101// 'apiProxy' is now ready to be used as middleware in a server.
102```
103
104- **context**: Determine which requests should be proxied to the target host.
105 (more on [context matching](#context-matching))
106- **options.target**: target host to proxy to. _(protocol + host)_
107
108(full list of [`http-proxy-middleware` configuration options](#options))
109
110#### createProxyMiddleware(uri [, config])
111
112```javascript
113// shorthand syntax for the example above:
114const apiProxy = createProxyMiddleware('http://www.example.org/api');
115```
116
117More about the [shorthand configuration](#shorthand).
118
119## Example
120
121An example with `express` server.
122
123```javascript
124// include dependencies
125const express = require('express');
126const { createProxyMiddleware } = require('http-proxy-middleware');
127
128// proxy middleware options
129const options = {
130 target: 'http://www.example.org', // target host
131 changeOrigin: true, // needed for virtual hosted sites
132 ws: true, // proxy websockets
133 pathRewrite: {
134 '^/api/old-path': '/api/new-path', // rewrite path
135 '^/api/remove/path': '/path', // remove base path
136 },
137 router: {
138 // when request.headers.host == 'dev.localhost:3000',
139 // override target 'http://www.example.org' to 'http://localhost:8000'
140 'dev.localhost:3000': 'http://localhost:8000',
141 },
142};
143
144// create the proxy (without context)
145const exampleProxy = createProxyMiddleware(options);
146
147// mount `exampleProxy` in web server
148const app = express();
149app.use('/api', exampleProxy);
150app.listen(3000);
151```
152
153## Context matching
154
155Providing an alternative way to decide which requests should be proxied; In case you are not able to use the server's [`path` parameter](http://expressjs.com/en/4x/api.html#app.use) to mount the proxy or when you need more flexibility.
156
157[RFC 3986 `path`](https://tools.ietf.org/html/rfc3986#section-3.3) is used for context matching.
158
159```ascii
160 foo://example.com:8042/over/there?name=ferret#nose
161 \_/ \______________/\_________/ \_________/ \__/
162 | | | | |
163 scheme authority path query fragment
164```
165
166- **path matching**
167
168 - `createProxyMiddleware({...})` - matches any path, all requests will be proxied.
169 - `createProxyMiddleware('/', {...})` - matches any path, all requests will be proxied.
170 - `createProxyMiddleware('/api', {...})` - matches paths starting with `/api`
171
172- **multiple path matching**
173
174 - `createProxyMiddleware(['/api', '/ajax', '/someotherpath'], {...})`
175
176- **wildcard path matching**
177
178 For fine-grained control you can use wildcard matching. Glob pattern matching is done by _micromatch_. Visit [micromatch](https://www.npmjs.com/package/micromatch) or [glob](https://www.npmjs.com/package/glob) for more globbing examples.
179
180 - `createProxyMiddleware('**', {...})` matches any path, all requests will be proxied.
181 - `createProxyMiddleware('**/*.html', {...})` matches any path which ends with `.html`
182 - `createProxyMiddleware('/*.html', {...})` matches paths directly under path-absolute
183 - `createProxyMiddleware('/api/**/*.html', {...})` matches requests ending with `.html` in the path of `/api`
184 - `createProxyMiddleware(['/api/**', '/ajax/**'], {...})` combine multiple patterns
185 - `createProxyMiddleware(['/api/**', '!**/bad.json'], {...})` exclusion
186
187 **Note**: In multiple path matching, you cannot use string paths and wildcard paths together.
188
189- **custom matching**
190
191 For full control you can provide a custom function to determine which requests should be proxied or not.
192
193 ```javascript
194 /**
195 * @return {Boolean}
196 */
197 const filter = function (pathname, req) {
198 return pathname.match('^/api') && req.method === 'GET';
199 };
200
201 const apiProxy = createProxyMiddleware(filter, {
202 target: 'http://www.example.org',
203 });
204 ```
205
206## Options
207
208### http-proxy-middleware options
209
210- **option.pathRewrite**: object/function, rewrite target's url path. Object-keys will be used as _RegExp_ to match paths.
211
212 ```javascript
213 // rewrite path
214 pathRewrite: {'^/old/api' : '/new/api'}
215
216 // remove path
217 pathRewrite: {'^/remove/api' : ''}
218
219 // add base path
220 pathRewrite: {'^/' : '/basepath/'}
221
222 // custom rewriting
223 pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }
224
225 // custom rewriting, returning Promise
226 pathRewrite: async function (path, req) {
227 const should_add_something = await httpRequestToDecideSomething(path);
228 if (should_add_something) path += "something";
229 return path;
230 }
231 ```
232
233- **option.router**: object/function, re-target `option.target` for specific requests.
234
235 ```javascript
236 // Use `host` and/or `path` to match requests. First match will be used.
237 // The order of the configuration matters.
238 router: {
239 'integration.localhost:3000' : 'http://localhost:8001', // host only
240 'staging.localhost:3000' : 'http://localhost:8002', // host only
241 'localhost:3000/api' : 'http://localhost:8003', // host + path
242 '/rest' : 'http://localhost:8004' // path only
243 }
244
245 // Custom router function (string target)
246 router: function(req) {
247 return 'http://localhost:8004';
248 }
249
250 // Custom router function (target object)
251 router: function(req) {
252 return {
253 protocol: 'https:', // The : is required
254 host: 'localhost',
255 port: 8004
256 };
257 }
258
259 // Asynchronous router function which returns promise
260 router: async function(req) {
261 const url = await doSomeIO();
262 return url;
263 }
264 ```
265
266- **option.logLevel**: string, ['debug', 'info', 'warn', 'error', 'silent']. Default: `'info'`
267
268- **option.logProvider**: function, modify or replace log provider. Default: `console`.
269
270 ```javascript
271 // simple replace
272 function logProvider(provider) {
273 // replace the default console log provider.
274 return require('winston');
275 }
276 ```
277
278 ```javascript
279 // verbose replacement
280 function logProvider(provider) {
281 const logger = new (require('winston').Logger)();
282
283 const myCustomProvider = {
284 log: logger.log,
285 debug: logger.debug,
286 info: logger.info,
287 warn: logger.warn,
288 error: logger.error,
289 };
290 return myCustomProvider;
291 }
292 ```
293
294### http-proxy events
295
296Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events):
297
298- **option.onError**: function, subscribe to http-proxy's `error` event for custom error handling.
299
300 ```javascript
301 function onError(err, req, res) {
302 res.writeHead(500, {
303 'Content-Type': 'text/plain',
304 });
305 res.end('Something went wrong. And we are reporting a custom error message.');
306 }
307 ```
308
309- **option.onProxyRes**: function, subscribe to http-proxy's `proxyRes` event.
310
311 ```javascript
312 function onProxyRes(proxyRes, req, res) {
313 proxyRes.headers['x-added'] = 'foobar'; // add new header to response
314 delete proxyRes.headers['x-removed']; // remove header from response
315 }
316 ```
317
318- **option.onProxyReq**: function, subscribe to http-proxy's `proxyReq` event.
319
320 ```javascript
321 function onProxyReq(proxyReq, req, res) {
322 // add custom header to request
323 proxyReq.setHeader('x-added', 'foobar');
324 // or log the req
325 }
326 ```
327
328- **option.onProxyReqWs**: function, subscribe to http-proxy's `proxyReqWs` event.
329
330 ```javascript
331 function onProxyReqWs(proxyReq, req, socket, options, head) {
332 // add custom header
333 proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
334 }
335 ```
336
337- **option.onOpen**: function, subscribe to http-proxy's `open` event.
338
339 ```javascript
340 function onOpen(proxySocket) {
341 // listen for messages coming FROM the target here
342 proxySocket.on('data', hybiParseAndLogMessage);
343 }
344 ```
345
346- **option.onClose**: function, subscribe to http-proxy's `close` event.
347
348 ```javascript
349 function onClose(res, socket, head) {
350 // view disconnected websocket connections
351 console.log('Client disconnected');
352 }
353 ```
354
355### http-proxy options
356
357The following options are provided by the underlying [http-proxy](https://github.com/nodejitsu/node-http-proxy#options) library.
358
359- **option.target**: url string to be parsed with the url module
360- **option.forward**: url string to be parsed with the url module
361- **option.agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects)
362- **option.ssl**: object to be passed to https.createServer()
363- **option.ws**: true/false: if you want to proxy websockets
364- **option.xfwd**: true/false, adds x-forward headers
365- **option.secure**: true/false, if you want to verify the SSL Certs
366- **option.toProxy**: true/false, passes the absolute URL as the `path` (useful for proxying to proxies)
367- **option.prependPath**: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path
368- **option.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).
369- **option.localAddress** : Local interface string to bind for outgoing connections
370- **option.changeOrigin**: true/false, Default: false - changes the origin of the host header to the target URL
371- **option.preserveHeaderKeyCase**: true/false, Default: false - specify whether you want to keep letter case of response header key
372- **option.auth** : Basic authentication i.e. 'user:password' to compute an Authorization header.
373- **option.hostRewrite**: rewrites the location hostname on (301/302/307/308) redirects.
374- **option.autoRewrite**: rewrites the location host/port on (301/302/307/308) redirects based on requested host/port. Default: false.
375- **option.protocolRewrite**: rewrites the location protocol on (301/302/307/308) redirects to 'http' or 'https'. Default: null.
376- **option.cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values:
377 - `false` (default): disable cookie rewriting
378 - String: new domain, for example `cookieDomainRewrite: "new.domain"`. To remove the domain, use `cookieDomainRewrite: ""`.
379 - Object: mapping of domains to new domains, use `"*"` to match all domains.
380 For example keep one domain unchanged, rewrite one domain and remove other domains:
381 ```json
382 cookieDomainRewrite: {
383 "unchanged.domain": "unchanged.domain",
384 "old.domain": "new.domain",
385 "*": ""
386 }
387 ```
388- **option.cookiePathRewrite**: rewrites path of `set-cookie` headers. Possible values:
389 - `false` (default): disable cookie rewriting
390 - String: new path, for example `cookiePathRewrite: "/newPath/"`. To remove the path, use `cookiePathRewrite: ""`. To set path to root use `cookiePathRewrite: "/"`.
391 - Object: mapping of paths to new paths, use `"*"` to match all paths.
392 For example, to keep one path unchanged, rewrite one path and remove other paths:
393 ```json
394 cookiePathRewrite: {
395 "/unchanged.path/": "/unchanged.path/",
396 "/old.path/": "/new.path/",
397 "*": ""
398 }
399 ```
400- **option.headers**: object, adds [request headers](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields). (Example: `{host:'www.example.org'}`)
401- **option.proxyTimeout**: timeout (in millis) when proxy receives no response from target
402- **option.timeout**: timeout (in millis) for incoming requests
403- **option.followRedirects**: true/false, Default: false - specify whether you want to follow redirects
404- **option.selfHandleResponse** true/false, if set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the `proxyRes` event
405- **option.buffer**: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e.g. If you read the body of a request into a field called 'req.rawbody' you could restream this field in the buffer option:
406
407 ```javascript
408 'use strict';
409
410 const streamify = require('stream-array');
411 const HttpProxy = require('http-proxy');
412 const proxy = new HttpProxy();
413
414 module.exports = (req, res, next) => {
415 proxy.web(
416 req,
417 res,
418 {
419 target: 'http://localhost:4003/',
420 buffer: streamify(req.rawBody),
421 },
422 next
423 );
424 };
425 ```
426
427## Shorthand
428
429Use 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.
430
431```javascript
432createProxyMiddleware('http://www.example.org:8000/api');
433// createProxyMiddleware('/api', {target: 'http://www.example.org:8000'});
434
435createProxyMiddleware('http://www.example.org:8000/api/books/*/**.json');
436// createProxyMiddleware('/api/books/*/**.json', {target: 'http://www.example.org:8000'});
437
438createProxyMiddleware('http://www.example.org:8000/api', { changeOrigin: true });
439// createProxyMiddleware('/api', {target: 'http://www.example.org:8000', changeOrigin: true});
440```
441
442### app.use(path, proxy)
443
444If you want to use the server's `app.use` `path` parameter to match requests;
445Create and mount the proxy without the http-proxy-middleware `context` parameter:
446
447```javascript
448app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));
449```
450
451`app.use` documentation:
452
453- express: http://expressjs.com/en/4x/api.html#app.use
454- connect: https://github.com/senchalabs/connect#mount-middleware
455- polka: https://github.com/lukeed/polka#usebase-fn
456
457## WebSocket
458
459```javascript
460// verbose api
461createProxyMiddleware('/', { target: 'http://echo.websocket.org', ws: true });
462
463// shorthand
464createProxyMiddleware('http://echo.websocket.org', { ws: true });
465
466// shorter shorthand
467createProxyMiddleware('ws://echo.websocket.org');
468```
469
470### External WebSocket upgrade
471
472In 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.
473
474```javascript
475const wsProxy = createProxyMiddleware('ws://echo.websocket.org', { changeOrigin: true });
476
477const app = express();
478app.use(wsProxy);
479
480const server = app.listen(3000);
481server.on('upgrade', wsProxy.upgrade); // <-- subscribe to http 'upgrade'
482```
483
484## Working examples
485
486View and play around with [working examples](https://github.com/chimurai/http-proxy-middleware/tree/master/examples).
487
488- Browser-Sync ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/browser-sync/index.js))
489- express ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/express/index.js))
490- connect ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/connect/index.js))
491- WebSocket ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/websocket/index.js))
492
493## Recipes
494
495View the [recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes) for common use cases.
496
497## Compatible servers
498
499`http-proxy-middleware` is compatible with the following servers:
500
501- [connect](https://www.npmjs.com/package/connect)
502- [express](https://www.npmjs.com/package/express)
503- [browser-sync](https://www.npmjs.com/package/browser-sync)
504- [lite-server](https://www.npmjs.com/package/lite-server)
505- [polka](https://github.com/lukeed/polka)
506- [grunt-contrib-connect](https://www.npmjs.com/package/grunt-contrib-connect)
507- [grunt-browser-sync](https://www.npmjs.com/package/grunt-browser-sync)
508- [gulp-connect](https://www.npmjs.com/package/gulp-connect)
509- [gulp-webserver](https://www.npmjs.com/package/gulp-webserver)
510
511Sample implementations can be found in the [server recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes/servers.md).
512
513## Tests
514
515Run the test suite:
516
517```bash
518# install dependencies
519$ yarn
520
521# linting
522$ yarn lint
523$ yarn lint:fix
524
525# building (compile typescript to js)
526$ yarn build
527
528# unit tests
529$ yarn test
530
531# code coverage
532$ yarn cover
533```
534
535## Changelog
536
537- [View changelog](https://github.com/chimurai/http-proxy-middleware/blob/master/CHANGELOG.md)
538
539## License
540
541The MIT License (MIT)
542
543Copyright (c) 2015-2020 Steven Chim