source: frontend/node_modules/http-proxy-middleware/README.md

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 11 days ago

Fix frontend appearance

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