http-proxy-middleware 2.0.4 → 3.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +254 -198
  2. package/dist/configuration.d.ts +2 -0
  3. package/dist/configuration.js +10 -0
  4. package/dist/debug.d.ts +5 -0
  5. package/dist/debug.js +8 -0
  6. package/dist/errors.d.ts +1 -1
  7. package/dist/errors.js +1 -1
  8. package/dist/get-plugins.d.ts +2 -0
  9. package/dist/get-plugins.js +15 -0
  10. package/dist/handlers/fix-request-body.d.ts +2 -1
  11. package/dist/handlers/index.js +5 -1
  12. package/dist/handlers/response-interceptor.js +10 -1
  13. package/dist/http-proxy-middleware.d.ts +3 -10
  14. package/dist/http-proxy-middleware.js +39 -50
  15. package/dist/index.d.ts +11 -3
  16. package/dist/index.js +15 -3
  17. package/dist/legacy/create-proxy-middleware.d.ts +11 -0
  18. package/dist/legacy/create-proxy-middleware.js +17 -0
  19. package/dist/legacy/index.d.ts +1 -0
  20. package/dist/legacy/index.js +17 -0
  21. package/dist/legacy/options-adapter.d.ts +6 -0
  22. package/dist/legacy/options-adapter.js +92 -0
  23. package/dist/legacy/public.d.ts +2 -0
  24. package/dist/legacy/public.js +5 -0
  25. package/dist/legacy/types.d.ts +110 -0
  26. package/dist/legacy/types.js +2 -0
  27. package/dist/logger.d.ts +2 -14
  28. package/dist/logger.js +20 -129
  29. package/dist/path-filter.d.ts +2 -0
  30. package/dist/{context-matcher.js → path-filter.js} +24 -24
  31. package/dist/path-rewriter.js +6 -6
  32. package/dist/plugins/default/debug-proxy-errors-plugin.d.ts +6 -0
  33. package/dist/plugins/default/debug-proxy-errors-plugin.js +61 -0
  34. package/dist/plugins/default/error-response-plugin.d.ts +2 -0
  35. package/dist/plugins/default/error-response-plugin.js +19 -0
  36. package/dist/plugins/default/index.d.ts +4 -0
  37. package/dist/plugins/default/index.js +20 -0
  38. package/dist/plugins/default/logger-plugin.d.ts +2 -0
  39. package/dist/plugins/default/logger-plugin.js +43 -0
  40. package/dist/plugins/default/proxy-events.d.ts +22 -0
  41. package/dist/plugins/default/proxy-events.js +33 -0
  42. package/dist/router.js +7 -7
  43. package/dist/status-code.d.ts +1 -0
  44. package/dist/status-code.js +24 -0
  45. package/dist/types.d.ts +71 -35
  46. package/dist/utils/function.d.ts +1 -0
  47. package/dist/utils/function.js +8 -0
  48. package/package.json +25 -19
  49. package/dist/_handlers.d.ts +0 -4
  50. package/dist/_handlers.js +0 -74
  51. package/dist/config-factory.d.ts +0 -6
  52. package/dist/config-factory.js +0 -80
  53. package/dist/context-matcher.d.ts +0 -2
package/README.md CHANGED
@@ -5,21 +5,27 @@
5
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
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
7
 
8
- 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).
8
+ Node.js proxying made simple. Configure proxy middleware with ease for [connect](https://github.com/senchalabs/connect), [express](https://github.com/expressjs/express), [next.js](https://github.com/vercel/next.js) and [many more](#compatible-servers).
9
9
 
10
10
  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)
11
11
 
12
12
  ## ⚠️ Note <!-- omit in toc -->
13
13
 
14
- This page is showing documentation for version v2.x.x ([release notes](https://github.com/chimurai/http-proxy-middleware/releases))
14
+ This page is showing documentation for version v3.x.x ([release notes](https://github.com/chimurai/http-proxy-middleware/releases))
15
15
 
16
- If you're looking for v0.x documentation. Go to:
17
- https://github.com/chimurai/http-proxy-middleware/tree/v0.21.0#readme
16
+ See [MIGRATION.md](https://github.com/chimurai/http-proxy-middleware/blob/master/MIGRATION.md) for details on how to migrate from v2.x.x to v3.x.x
17
+
18
+ If you're looking for older documentation. Go to:
19
+
20
+ - <https://github.com/chimurai/http-proxy-middleware/tree/v2.0.4#readme>
21
+ - <https://github.com/chimurai/http-proxy-middleware/tree/v0.21.0#readme>
18
22
 
19
23
  ## TL;DR <!-- omit in toc -->
20
24
 
21
25
  Proxy `/api` requests to `http://www.example.org`
22
26
 
27
+ :bulb: **Tip:** Set the option `changeOrigin` to `true` for [name-based virtual hosted sites](http://en.wikipedia.org/wiki/Virtual_hosting#Name-based).
28
+
23
29
  ```javascript
24
30
  // javascript
25
31
 
@@ -28,10 +34,18 @@ const { createProxyMiddleware } = require('http-proxy-middleware');
28
34
 
29
35
  const app = express();
30
36
 
31
- app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));
37
+ app.use(
38
+ '/api',
39
+ createProxyMiddleware({
40
+ target: 'http://www.example.org/secret',
41
+ changeOrigin: true,
42
+ })
43
+ );
44
+
32
45
  app.listen(3000);
33
46
 
34
- // http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar
47
+ // proxy and change the base path from "/api" to "/secret"
48
+ // http://localhost:3000/api/foo/bar -> http://www.example.org/secret/foo/bar
35
49
  ```
36
50
 
37
51
  ```typescript
@@ -42,32 +56,44 @@ import { createProxyMiddleware, Filter, Options, RequestHandler } from 'http-pro
42
56
 
43
57
  const app = express();
44
58
 
45
- app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));
59
+ app.use(
60
+ '/api',
61
+ createProxyMiddleware({
62
+ target: 'http://www.example.org/api',
63
+ changeOrigin: true,
64
+ })
65
+ );
66
+
46
67
  app.listen(3000);
47
68
 
69
+ // proxy and keep the same base path "/api"
48
70
  // http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar
49
71
  ```
50
72
 
51
73
  _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
74
 
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
75
  ## Table of Contents <!-- omit in toc -->
56
76
 
77
+ <!-- // spell-checker:disable -->
78
+
57
79
  - [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)
80
+ - [Basic usage](#basic-usage)
81
+ - [Express Server Example](#express-server-example)
66
82
  - [app.use(path, proxy)](#appusepath-proxy)
83
+ - [Options](#options)
84
+ - [`pathFilter` (string, []string, glob, []glob, function)](#pathfilter-string-string-glob-glob-function)
85
+ - [`pathRewrite` (object/function)](#pathrewrite-objectfunction)
86
+ - [`router` (object/function)](#router-objectfunction)
87
+ - [`plugins` (Array)](#plugins-array)
88
+ - [`ejectPlugins` (boolean) default: `false`](#ejectplugins-boolean-default-false)
89
+ - [`logger` (Object)](#logger-object)
90
+ - [`http-proxy` events](#http-proxy-events)
91
+ - [`http-proxy` options](#http-proxy-options)
67
92
  - [WebSocket](#websocket)
68
93
  - [External WebSocket upgrade](#external-websocket-upgrade)
69
94
  - [Intercept and manipulate requests](#intercept-and-manipulate-requests)
70
95
  - [Intercept and manipulate responses](#intercept-and-manipulate-responses)
96
+ - [Debugging](#debugging)
71
97
  - [Working examples](#working-examples)
72
98
  - [Recipes](#recipes)
73
99
  - [Compatible servers](#compatible-servers)
@@ -75,45 +101,35 @@ _All_ `http-proxy` [options](https://github.com/nodejitsu/node-http-proxy#option
75
101
  - [Changelog](#changelog)
76
102
  - [License](#license)
77
103
 
104
+ <!-- // spell-checker:enable -->
105
+
78
106
  ## Install
79
107
 
80
- ```bash
81
- $ npm install --save-dev http-proxy-middleware
108
+ ```shell
109
+ npm install --save-dev http-proxy-middleware
82
110
  ```
83
111
 
84
- ## Core concept
112
+ ## Basic usage
85
113
 
86
- Proxy middleware configuration.
87
-
88
- #### createProxyMiddleware([context,] config)
114
+ Create and configure a proxy middleware with: `createProxyMiddleware(config)`.
89
115
 
90
116
  ```javascript
91
117
  const { createProxyMiddleware } = require('http-proxy-middleware');
92
118
 
93
- const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org' });
94
- // \____/ \_____________________________/
95
- // | |
96
- // context options
119
+ const apiProxy = createProxyMiddleware({
120
+ target: 'http://www.example.org',
121
+ changeOrigin: true,
122
+ });
97
123
 
98
124
  // 'apiProxy' is now ready to be used as middleware in a server.
99
125
  ```
100
126
 
101
- - **context**: Determine which requests should be proxied to the target host.
102
- (more on [context matching](#context-matching))
103
127
  - **options.target**: target host to proxy to. _(protocol + host)_
128
+ - **options.changeOrigin**: for virtual hosted sites
104
129
 
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:
111
- const apiProxy = createProxyMiddleware('http://www.example.org/api');
112
- ```
113
-
114
- More about the [shorthand configuration](#shorthand).
130
+ - see full list of [`http-proxy-middleware` configuration options](#options)
115
131
 
116
- ## Example
132
+ ## Express Server Example
117
133
 
118
134
  An example with `express` server.
119
135
 
@@ -122,65 +138,71 @@ An example with `express` server.
122
138
  const express = require('express');
123
139
  const { createProxyMiddleware } = require('http-proxy-middleware');
124
140
 
141
+ const app = express();
142
+
125
143
  // proxy middleware options
126
144
  /** @type {import('http-proxy-middleware/dist/types').Options} */
127
145
  const options = {
128
- target: 'http://www.example.org', // target host
146
+ target: 'http://www.example.org/api', // target host with the same base path
129
147
  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
148
  };
141
149
 
142
- // create the proxy (without context)
150
+ // create the proxy
143
151
  const exampleProxy = createProxyMiddleware(options);
144
152
 
145
153
  // mount `exampleProxy` in web server
146
- const app = express();
147
154
  app.use('/api', exampleProxy);
148
155
  app.listen(3000);
149
156
  ```
150
157
 
151
- ## Context matching
152
-
153
- 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.
158
+ ### app.use(path, proxy)
154
159
 
155
- [RFC 3986 `path`](https://tools.ietf.org/html/rfc3986#section-3.3) is used for context matching.
160
+ If you want to use the server's `app.use` `path` parameter to match requests.
161
+ Use `pathFilter` option to further include/exclude requests which you want to proxy.
156
162
 
157
- ```ascii
158
- foo://example.com:8042/over/there?name=ferret#nose
159
- \_/ \______________/\_________/ \_________/ \__/
160
- | | | | |
161
- scheme authority path query fragment
163
+ ```javascript
164
+ app.use(
165
+ createProxyMiddleware({
166
+ target: 'http://www.example.org/api',
167
+ changeOrigin: true,
168
+ pathFilter: '/api/proxy-only-this-path',
169
+ })
170
+ );
162
171
  ```
163
172
 
173
+ `app.use` documentation:
174
+
175
+ - express: <http://expressjs.com/en/4x/api.html#app.use>
176
+ - connect: <https://github.com/senchalabs/connect#mount-middleware>
177
+ - polka: <https://github.com/lukeed/polka#usebase-fn>
178
+
179
+ ## Options
180
+
181
+ http-proxy-middleware options:
182
+
183
+ ### `pathFilter` (string, []string, glob, []glob, function)
184
+
185
+ Narrow down which requests should be proxied. The `path` used for filtering is the `request.url` pathname. In Express, this is the `path` relative to the mount-point of the proxy.
186
+
164
187
  - **path matching**
165
188
 
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`
189
+ - `createProxyMiddleware({...})` - matches any path, all requests will be proxied when `pathFilter` is not configured.
190
+ - `createProxyMiddleware({ pathFilter: '/api', ...})` - matches paths starting with `/api`
169
191
 
170
192
  - **multiple path matching**
171
193
 
172
- - `createProxyMiddleware(['/api', '/ajax', '/someotherpath'], {...})`
194
+ - `createProxyMiddleware({ pathFilter: ['/api', '/ajax', '/someotherpath'], ...})`
173
195
 
174
196
  - **wildcard path matching**
175
197
 
176
198
  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
199
 
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
200
+ - `createProxyMiddleware({ pathFilter: '**', ...})` matches any path, all requests will be proxied.
201
+ - `createProxyMiddleware({ pathFilter: '**/*.html', ...})` matches any path which ends with `.html`
202
+ - `createProxyMiddleware({ pathFilter: '/*.html', ...})` matches paths directly under path-absolute
203
+ - `createProxyMiddleware({ pathFilter: '/api/**/*.html', ...})` matches requests ending with `.html` in the path of `/api`
204
+ - `createProxyMiddleware({ pathFilter: ['/api/**', '/ajax/**'], ...})` combine multiple patterns
205
+ - `createProxyMiddleware({ pathFilter: ['/api/**', '!**/bad.json'], ...})` exclusion
184
206
 
185
207
  **Note**: In multiple path matching, you cannot use string paths and wildcard paths together.
186
208
 
@@ -192,108 +214,154 @@ Providing an alternative way to decide which requests should be proxied; In case
192
214
  /**
193
215
  * @return {Boolean}
194
216
  */
195
- const filter = function (pathname, req) {
196
- return pathname.match('^/api') && req.method === 'GET';
217
+ const pathFilter = function (path, req) {
218
+ return path.match('^/api') && req.method === 'GET';
197
219
  };
198
220
 
199
- const apiProxy = createProxyMiddleware(filter, {
221
+ const apiProxy = createProxyMiddleware({
200
222
  target: 'http://www.example.org',
223
+ pathFilter: pathFilter,
201
224
  });
202
225
  ```
203
226
 
204
- ## Options
227
+ ### `pathRewrite` (object/function)
205
228
 
206
- ### http-proxy-middleware options
229
+ Rewrite target's url path. Object-keys will be used as _RegExp_ to match paths.
207
230
 
208
- - **option.pathRewrite**: object/function, rewrite target's url path. Object-keys will be used as _RegExp_ to match paths.
231
+ ```javascript
232
+ // rewrite path
233
+ pathRewrite: {'^/old/api' : '/new/api'}
209
234
 
210
- ```javascript
211
- // rewrite path
212
- pathRewrite: {'^/old/api' : '/new/api'}
235
+ // remove path
236
+ pathRewrite: {'^/remove/api' : ''}
213
237
 
214
- // remove path
215
- pathRewrite: {'^/remove/api' : ''}
238
+ // add base path
239
+ pathRewrite: {'^/' : '/basepath/'}
216
240
 
217
- // add base path
218
- pathRewrite: {'^/' : '/basepath/'}
241
+ // custom rewriting
242
+ pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }
219
243
 
220
- // custom rewriting
221
- pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }
244
+ // custom rewriting, returning Promise
245
+ pathRewrite: async function (path, req) {
246
+ const should_add_something = await httpRequestToDecideSomething(path);
247
+ if (should_add_something) path += "something";
248
+ return path;
249
+ }
250
+ ```
222
251
 
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
- ```
252
+ ### `router` (object/function)
230
253
 
231
- - **option.router**: object/function, re-target `option.target` for specific requests.
254
+ Re-target `option.target` for specific requests.
232
255
 
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
- }
256
+ ```javascript
257
+ // Use `host` and/or `path` to match requests. First match will be used.
258
+ // The order of the configuration matters.
259
+ router: {
260
+ 'integration.localhost:3000' : 'http://localhost:8001', // host only
261
+ 'staging.localhost:3000' : 'http://localhost:8002', // host only
262
+ 'localhost:3000/api' : 'http://localhost:8003', // host + path
263
+ '/rest' : 'http://localhost:8004' // path only
264
+ }
265
+
266
+ // Custom router function (string target)
267
+ router: function(req) {
268
+ return 'http://localhost:8004';
269
+ }
270
+
271
+ // Custom router function (target object)
272
+ router: function(req) {
273
+ return {
274
+ protocol: 'https:', // The : is required
275
+ host: 'localhost',
276
+ port: 8004
277
+ };
278
+ }
242
279
 
243
- // Custom router function (string target)
244
- router: function(req) {
245
- return 'http://localhost:8004';
246
- }
280
+ // Asynchronous router function which returns promise
281
+ router: async function(req) {
282
+ const url = await doSomeIO();
283
+ return url;
284
+ }
285
+ ```
247
286
 
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
- }
287
+ ### `plugins` (Array)
256
288
 
257
- // Asynchronous router function which returns promise
258
- router: async function(req) {
259
- const url = await doSomeIO();
260
- return url;
261
- }
262
- ```
289
+ ```js
290
+ const simpleRequestLogger = (proxyServer, options) => {
291
+ proxyServer.on('proxyReq', (proxyReq, req, res) => {
292
+ console.log(`[HPM] [${req.method}] ${req.url}`); // outputs: [HPM] GET /users
293
+ });
294
+ },
295
+
296
+ const config = {
297
+ target: `http://example.org`,
298
+ changeOrigin: true,
299
+ plugins: [simpleRequestLogger],
300
+ };
301
+ ```
263
302
 
264
- - **option.logLevel**: string, ['debug', 'info', 'warn', 'error', 'silent']. Default: `'info'`
303
+ ### `ejectPlugins` (boolean) default: `false`
265
304
 
266
- - **option.logProvider**: function, modify or replace log provider. Default: `console`.
305
+ If you're not satisfied with the pre-configured plugins, you can eject them by configuring `ejectPlugins: true`.
267
306
 
268
- ```javascript
269
- // simple replace
270
- function logProvider(provider) {
271
- // replace the default console log provider.
272
- return require('winston');
273
- }
274
- ```
307
+ NOTE: register your own error handlers to prevent server from crashing.
275
308
 
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
- ```
309
+ ```js
310
+ // eject default plugins and manually add them back
311
+
312
+ const {
313
+ debugProxyErrorsPlugin, // subscribe to proxy errors to prevent server from crashing
314
+ loggerPlugin, // log proxy events to a logger (ie. console)
315
+ errorResponsePlugin, // return 5xx response on proxy error
316
+ proxyEventsPlugin, // implements the "on:" option
317
+ } = require('http-proxy-middleware');
318
+
319
+ createProxyMiddleware({
320
+ target: `http://example.org`,
321
+ changeOrigin: true,
322
+ ejectPlugins: true,
323
+ plugins: [debugProxyErrorsPlugin, loggerPlugin, errorResponsePlugin, proxyEventsPlugin],
324
+ });
325
+ ```
326
+
327
+ ### `logger` (Object)
328
+
329
+ Configure a logger to output information from http-proxy-middleware: ie. `console`, `winston`, `pino`, `bunyan`, `log4js`, etc...
291
330
 
292
- ### http-proxy events
331
+ Only `info`, `warn`, `error` are used internally for compatibility across different loggers.
293
332
 
294
- Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events):
333
+ If you use `winston`, make sure to enable interpolation: <https://github.com/winstonjs/winston#string-interpolation>
295
334
 
296
- - **option.onError**: function, subscribe to http-proxy's `error` event for custom error handling.
335
+ See also logger recipes ([recipes/logger.md](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md)) for more details.
336
+
337
+ ```javascript
338
+ createProxyMiddleware({
339
+ logger: console,
340
+ });
341
+ ```
342
+
343
+ ## `http-proxy` events
344
+
345
+ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events) with the `on` option:
346
+
347
+ ```js
348
+ createProxyMiddleware({
349
+ target: 'http://www.example.org',
350
+ on: {
351
+ proxyReq: (proxyReq, req, res) => {
352
+ /* handle proxyReq */
353
+ },
354
+ proxyRes: (proxyRes, req, res) => {
355
+ /* handle proxyRes */
356
+ },
357
+ error: (err, req, res) => {
358
+ /* handle error */
359
+ },
360
+ },
361
+ });
362
+ ```
363
+
364
+ - **option.on.error**: function, subscribe to http-proxy's `error` event for custom error handling.
297
365
 
298
366
  ```javascript
299
367
  function onError(err, req, res, target) {
@@ -304,7 +372,7 @@ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#li
304
372
  }
305
373
  ```
306
374
 
307
- - **option.onProxyRes**: function, subscribe to http-proxy's `proxyRes` event.
375
+ - **option.on.proxyRes**: function, subscribe to http-proxy's `proxyRes` event.
308
376
 
309
377
  ```javascript
310
378
  function onProxyRes(proxyRes, req, res) {
@@ -313,7 +381,7 @@ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#li
313
381
  }
314
382
  ```
315
383
 
316
- - **option.onProxyReq**: function, subscribe to http-proxy's `proxyReq` event.
384
+ - **option.on.proxyReq**: function, subscribe to http-proxy's `proxyReq` event.
317
385
 
318
386
  ```javascript
319
387
  function onProxyReq(proxyReq, req, res) {
@@ -323,7 +391,7 @@ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#li
323
391
  }
324
392
  ```
325
393
 
326
- - **option.onProxyReqWs**: function, subscribe to http-proxy's `proxyReqWs` event.
394
+ - **option.on.proxyReqWs**: function, subscribe to http-proxy's `proxyReqWs` event.
327
395
 
328
396
  ```javascript
329
397
  function onProxyReqWs(proxyReq, req, socket, options, head) {
@@ -332,7 +400,7 @@ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#li
332
400
  }
333
401
  ```
334
402
 
335
- - **option.onOpen**: function, subscribe to http-proxy's `open` event.
403
+ - **option.on.open**: function, subscribe to http-proxy's `open` event.
336
404
 
337
405
  ```javascript
338
406
  function onOpen(proxySocket) {
@@ -341,7 +409,7 @@ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#li
341
409
  }
342
410
  ```
343
411
 
344
- - **option.onClose**: function, subscribe to http-proxy's `close` event.
412
+ - **option.on.close**: function, subscribe to http-proxy's `close` event.
345
413
 
346
414
  ```javascript
347
415
  function onClose(res, socket, head) {
@@ -350,7 +418,7 @@ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#li
350
418
  }
351
419
  ```
352
420
 
353
- ### http-proxy options
421
+ ## `http-proxy` options
354
422
 
355
423
  The following options are provided by the underlying [http-proxy](https://github.com/nodejitsu/node-http-proxy#options) library.
356
424
 
@@ -372,10 +440,12 @@ The following options are provided by the underlying [http-proxy](https://github
372
440
  - **option.autoRewrite**: rewrites the location host/port on (301/302/307/308) redirects based on requested host/port. Default: false.
373
441
  - **option.protocolRewrite**: rewrites the location protocol on (301/302/307/308) redirects to 'http' or 'https'. Default: null.
374
442
  - **option.cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values:
443
+
375
444
  - `false` (default): disable cookie rewriting
376
445
  - String: new domain, for example `cookieDomainRewrite: "new.domain"`. To remove the domain, use `cookieDomainRewrite: ""`.
377
446
  - Object: mapping of domains to new domains, use `"*"` to match all domains.
378
447
  For example keep one domain unchanged, rewrite one domain and remove other domains:
448
+
379
449
  ```json
380
450
  cookieDomainRewrite: {
381
451
  "unchanged.domain": "unchanged.domain",
@@ -383,11 +453,14 @@ The following options are provided by the underlying [http-proxy](https://github
383
453
  "*": ""
384
454
  }
385
455
  ```
456
+
386
457
  - **option.cookiePathRewrite**: rewrites path of `set-cookie` headers. Possible values:
458
+
387
459
  - `false` (default): disable cookie rewriting
388
460
  - String: new path, for example `cookiePathRewrite: "/newPath/"`. To remove the path, use `cookiePathRewrite: ""`. To set path to root use `cookiePathRewrite: "/"`.
389
461
  - Object: mapping of paths to new paths, use `"*"` to match all paths.
390
462
  For example, to keep one path unchanged, rewrite one path and remove other paths:
463
+
391
464
  ```json
392
465
  cookiePathRewrite: {
393
466
  "/unchanged.path/": "/unchanged.path/",
@@ -395,6 +468,7 @@ The following options are provided by the underlying [http-proxy](https://github
395
468
  "*": ""
396
469
  }
397
470
  ```
471
+
398
472
  - **option.headers**: object, adds [request headers](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields). (Example: `{host:'www.example.org'}`)
399
473
  - **option.proxyTimeout**: timeout (in millis) when proxy receives no response from target
400
474
  - **option.timeout**: timeout (in millis) for incoming requests
@@ -422,47 +496,11 @@ The following options are provided by the underlying [http-proxy](https://github
422
496
  };
423
497
  ```
424
498
 
425
- ## Shorthand
426
-
427
- 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.
428
-
429
- ```javascript
430
- createProxyMiddleware('http://www.example.org:8000/api');
431
- // createProxyMiddleware('/api', {target: 'http://www.example.org:8000'});
432
-
433
- createProxyMiddleware('http://www.example.org:8000/api/books/*/**.json');
434
- // createProxyMiddleware('/api/books/*/**.json', {target: 'http://www.example.org:8000'});
435
-
436
- createProxyMiddleware('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
-
442
- If you want to use the server's `app.use` `path` parameter to match requests;
443
- Create and mount the proxy without the http-proxy-middleware `context` parameter:
444
-
445
- ```javascript
446
- app.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
499
  ## WebSocket
456
500
 
457
501
  ```javascript
458
502
  // verbose api
459
- createProxyMiddleware('/', { target: 'http://echo.websocket.org', ws: true });
460
-
461
- // shorthand
462
- createProxyMiddleware('http://echo.websocket.org', { ws: true });
463
-
464
- // shorter shorthand
465
- createProxyMiddleware('ws://echo.websocket.org');
503
+ createProxyMiddleware({ pathFilter: '/', target: 'http://echo.websocket.org', ws: true });
466
504
  ```
467
505
 
468
506
  ### External WebSocket upgrade
@@ -470,7 +508,7 @@ createProxyMiddleware('ws://echo.websocket.org');
470
508
  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.
471
509
 
472
510
  ```javascript
473
- const wsProxy = createProxyMiddleware('ws://echo.websocket.org', { changeOrigin: true });
511
+ const wsProxy = createProxyMiddleware({ target: 'ws://echo.websocket.org', changeOrigin: true });
474
512
 
475
513
  const app = express();
476
514
  app.use(wsProxy);
@@ -494,7 +532,9 @@ const proxy = createProxyMiddleware({
494
532
  /**
495
533
  * Fix bodyParser
496
534
  **/
497
- onProxyReq: fixRequestBody,
535
+ on: {
536
+ proxyReq: fixRequestBody,
537
+ },
498
538
  });
499
539
  ```
500
540
 
@@ -522,15 +562,30 @@ const proxy = createProxyMiddleware({
522
562
  /**
523
563
  * Intercept response and replace 'Hello' with 'Goodbye'
524
564
  **/
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
- }),
565
+ on: {
566
+ proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
567
+ const response = responseBuffer.toString('utf8'); // convert buffer to string
568
+ return response.replace('Hello', 'Goodbye'); // manipulate response and return the result
569
+ }),
570
+ },
529
571
  });
530
572
  ```
531
573
 
532
574
  Check out [interception recipes](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md#readme) for more examples.
533
575
 
576
+ ## Debugging
577
+
578
+ Configure the `DEBUG` environment variable enable debug logging.
579
+
580
+ See [`debug`](https://github.com/debug-js/debug#readme) project for more options.
581
+
582
+ ```shell
583
+ DEBUG=http-proxy-middleware* node server.js
584
+
585
+ $ http-proxy-middleware proxy created +0ms
586
+ $ http-proxy-middleware proxying request to target: 'http://www.example.org' +359ms
587
+ ```
588
+
534
589
  ## Working examples
535
590
 
536
591
  View and play around with [working examples](https://github.com/chimurai/http-proxy-middleware/tree/master/examples).
@@ -551,6 +606,7 @@ View the [recipes](https://github.com/chimurai/http-proxy-middleware/tree/master
551
606
 
552
607
  - [connect](https://www.npmjs.com/package/connect)
553
608
  - [express](https://www.npmjs.com/package/express)
609
+ - [next.js](https://www.npmjs.com/package/next)
554
610
  - [fastify](https://www.npmjs.com/package/fastify)
555
611
  - [browser-sync](https://www.npmjs.com/package/browser-sync)
556
612
  - [lite-server](https://www.npmjs.com/package/lite-server)