You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

598 lines
22 KiB

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