Skip to content

Commit 1dc79c5

Browse files
committed
feat(legacyCreateProxyMiddleware): adapter with legacy behavior
1 parent e094312 commit 1dc79c5

14 files changed

+492
-22
lines changed

MIGRATION.md

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
# Migration guide
2+
3+
- [v2 to v3 adapter](#v2-to-v3-adapter)
4+
- [`legacyCreateProxyMiddleware`](#legacycreateproxymiddleware)
5+
- [v3 breaking changes](#v3-breaking-changes)
6+
- [Removed `req.url` patching](#removed-requrl-patching)
7+
- [Removed "shorthand" usage](#removed-shorthand-usage)
8+
- [Removed `context` argument](#removed-context-argument)
9+
- [Removed `logProvider` and `logLevel` options](#removed-logprovider-and-loglevel-options)
10+
- [Refactored proxy events](#refactored-proxy-events)
11+
12+
## v2 to v3 adapter
13+
14+
### `legacyCreateProxyMiddleware`
15+
16+
Use the adapter to use v3 without changing too much of your v2 code and configuration.
17+
18+
NOTE: `legacyCreateProxyMiddleware` will be removed in a future version.
19+
20+
```js
21+
// before
22+
const { createProxyMiddleware } = require('http-proxy-middleware');
23+
24+
createProxyMiddleware(...);
25+
26+
// after
27+
const { legacyCreateProxyMiddleware } = require('http-proxy-middleware');
28+
29+
legacyCreateProxyMiddleware(...);
30+
```
31+
32+
```ts
33+
// before
34+
import { createProxyMiddleware, Options } from 'http-proxy-middleware';
35+
36+
createProxyMiddleware(...);
37+
38+
// after
39+
import { legacyCreateProxyMiddleware, LegacyOptions } from 'http-proxy-middleware';
40+
41+
legacyCreateProxyMiddleware(...);
42+
```
43+
44+
## v3 breaking changes
45+
46+
### Removed `req.url` patching
47+
48+
```js
49+
// before
50+
app.use('/user', proxy({ target: 'http://www.example.org' }));
51+
52+
// after
53+
app.use('/user', proxy({ target: 'http://www.example.org/user' }));
54+
```
55+
56+
### Removed "shorthand" usage
57+
58+
```js
59+
// before
60+
createProxyMiddleware('http:/www.example.org');
61+
62+
// after
63+
createProxyMiddleware({ target: 'http:/www.example.org' });
64+
```
65+
66+
### Removed `context` argument
67+
68+
See [recipes/pathFilter.md](./recipes/pathFilter.md) for more information.
69+
70+
```js
71+
// before
72+
createProxyMiddleware('/path', { target: 'http://www.example.org' });
73+
74+
// after
75+
createProxyMiddleware({
76+
target: 'http://www.example.org',
77+
pathFilter: '/path',
78+
});
79+
```
80+
81+
### Removed `logProvider` and `logLevel` options
82+
83+
Use your external logging library to control the logging level.
84+
85+
Only `info`, `warn`, `error` are used internally for compatibility across different loggers.
86+
87+
If you use `winston`, make sure to enable interpolation: <https://github.com/winstonjs/winston#string-interpolation>
88+
89+
````js
90+
91+
See [recipes/logger.md](./recipes/logger.md) for more information.
92+
93+
```js
94+
// new
95+
createProxyMiddleware({
96+
target: 'http://www.example.org',
97+
logger: console,
98+
});
99+
````
100+
101+
### Refactored proxy events
102+
103+
See [recipes/proxy-events.md](./recipes/proxy-events.md) for more information.
104+
105+
```js
106+
// before
107+
createProxyMiddleware({
108+
target: 'http://www.example.org',
109+
onError: () => {},
110+
onProxyReq: () => {},
111+
onProxyRes: () => {},
112+
onProxyReqWs: () => {},
113+
onOpen: () => {},
114+
onClose: () => {},
115+
});
116+
117+
// after
118+
createProxyMiddleware({
119+
target: 'http://www.example.org',
120+
on: {
121+
error: () => {},
122+
proxyReq: () => {},
123+
proxyRes: () => {},
124+
proxyReqWs: () => {},
125+
open: () => {},
126+
close: () => {},
127+
},
128+
});
129+
```

README.md

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,21 @@ Powered by the popular Nodejitsu [`http-proxy`](https://github.com/nodejitsu/nod
1111

1212
## ⚠️ Note <!-- omit in toc -->
1313

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))
1515

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>
1822

1923
## TL;DR <!-- omit in toc -->
2024

2125
Proxy `/api` requests to `http://www.example.org`
2226

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+
2329
```javascript
2430
// javascript
2531

@@ -58,8 +64,6 @@ app.listen(3000);
5864

5965
_All_ `http-proxy` [options](https://github.com/nodejitsu/node-http-proxy#options) can be used, along with some extra `http-proxy-middleware` [options](#options).
6066

61-
:bulb: **Tip:** Set the option `changeOrigin` to `true` for [name-based virtual hosted sites](http://en.wikipedia.org/wiki/Virtual_hosting#Name-based).
62-
6367
## Table of Contents <!-- omit in toc -->
6468

6569
<!-- // spell-checker:disable -->
@@ -160,9 +164,9 @@ app.use(
160164

161165
`app.use` documentation:
162166

163-
- express: http://expressjs.com/en/4x/api.html#app.use
164-
- connect: https://github.com/senchalabs/connect#mount-middleware
165-
- polka: https://github.com/lukeed/polka#usebase-fn
167+
- express: <http://expressjs.com/en/4x/api.html#app.use>
168+
- connect: <https://github.com/senchalabs/connect#mount-middleware>
169+
- polka: <https://github.com/lukeed/polka#usebase-fn>
166170

167171
## Options
168172

@@ -316,6 +320,10 @@ createProxyMiddleware({
316320

317321
Configure a logger to output information from http-proxy-middleware: ie. `console`, `winston`, `pino`, `bunyan`, `log4js`, etc...
318322

323+
Only `info`, `warn`, `error` are used internally for compatibility across different loggers.
324+
325+
If you use `winston`, make sure to enable interpolation: <https://github.com/winstonjs/winston#string-interpolation>
326+
319327
See also logger recipes ([recipes/logger.md](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md)) for more details.
320328

321329
```javascript
@@ -424,29 +432,35 @@ The following options are provided by the underlying [http-proxy](https://github
424432
- **option.autoRewrite**: rewrites the location host/port on (301/302/307/308) redirects based on requested host/port. Default: false.
425433
- **option.protocolRewrite**: rewrites the location protocol on (301/302/307/308) redirects to 'http' or 'https'. Default: null.
426434
- **option.cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values:
435+
427436
- `false` (default): disable cookie rewriting
428437
- String: new domain, for example `cookieDomainRewrite: "new.domain"`. To remove the domain, use `cookieDomainRewrite: ""`.
429438
- Object: mapping of domains to new domains, use `"*"` to match all domains.
430439
For example keep one domain unchanged, rewrite one domain and remove other domains:
440+
431441
```json
432442
cookieDomainRewrite: {
433443
"unchanged.domain": "unchanged.domain",
434444
"old.domain": "new.domain",
435445
"*": ""
436446
}
437447
```
448+
438449
- **option.cookiePathRewrite**: rewrites path of `set-cookie` headers. Possible values:
450+
439451
- `false` (default): disable cookie rewriting
440452
- String: new path, for example `cookiePathRewrite: "/newPath/"`. To remove the path, use `cookiePathRewrite: ""`. To set path to root use `cookiePathRewrite: "/"`.
441453
- Object: mapping of paths to new paths, use `"*"` to match all paths.
442454
For example, to keep one path unchanged, rewrite one path and remove other paths:
455+
443456
```json
444457
cookiePathRewrite: {
445458
"/unchanged.path/": "/unchanged.path/",
446459
"/old.path/": "/new.path/",
447460
"*": ""
448461
}
449462
```
463+
450464
- **option.headers**: object, adds [request headers](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields). (Example: `{host:'www.example.org'}`)
451465
- **option.proxyTimeout**: timeout (in millis) when proxy receives no response from target
452466
- **option.timeout**: timeout (in millis) for incoming requests

cspell.json

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,21 @@
22
"language": "en",
33
"spellCheckDelayMs": 500,
44
"dictionaries": ["node", "npm", "typescript", "contributors"],
5-
"ignorePaths": ["node_modules/**", "coverage/**", "dist/**", "package.json", "yarn.lock"],
5+
"ignorePaths": [
6+
"node_modules/**",
7+
"coverage/**",
8+
"dist/**",
9+
"package.json",
10+
"yarn.lock",
11+
"*.tgz"
12+
],
613
"dictionaryDefinitions": [
714
{
815
"name": "contributors",
916
"path": "CONTRIBUTORS.txt"
1017
}
1118
],
12-
"ignoreRegExpList": ["[a-z]+path"],
19+
"ignoreRegExpList": ["[a-z]+path", "\\]\\(#[a-z-]+\\)"],
1320
"words": [
1421
"camelcase",
1522
"codesandbox",

examples/connect/index.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ const { createProxyMiddleware } = require('../../dist'); // require('http-proxy-
1111
const jsonPlaceholderProxy = createProxyMiddleware({
1212
target: 'http://jsonplaceholder.typicode.com/users',
1313
changeOrigin: true, // for vhosted sites, changes host header to match to target's host
14-
logLevel: 'debug',
1514
});
1615

1716
const app = connect();

examples/express/index.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ const { createProxyMiddleware } = require('../../dist'); // require('http-proxy-
1010
const jsonPlaceholderProxy = createProxyMiddleware({
1111
target: 'http://jsonplaceholder.typicode.com/users',
1212
changeOrigin: true, // for vhosted sites, changes host header to match to target's host
13-
logLevel: 'debug',
1413
logger: console,
1514
});
1615

recipes/websocket.md

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@ This example will create a proxy middleware with websocket support.
55
```javascript
66
const { createProxyMiddleware } = require('http-proxy-middleware');
77

8-
const socketProxy = createProxyMiddleware('/socket', {
8+
const socketProxy = createProxyMiddleware({
99
target: 'http://localhost:3000',
10+
pathFilter: '/socket',
1011
ws: true,
1112
});
1213
```
@@ -21,12 +22,13 @@ const { createProxyMiddleware } = require('http-proxy-middleware');
2122
const options = {
2223
target: 'http://localhost:3000',
2324
ws: true,
25+
pathFilter: '/socket',
2426
pathRewrite: {
2527
'^/socket': '',
2628
},
2729
};
2830

29-
const socketProxy = createProxyMiddleware('/socket', options);
31+
const socketProxy = createProxyMiddleware(options);
3032
```
3133

3234
## WebSocket - Server update subscription
@@ -38,8 +40,9 @@ Subscribe to server's upgrade event.
3840
```javascript
3941
const { createProxyMiddleware } = require('http-proxy-middleware');
4042

41-
const socketProxy = createProxyMiddleware('/socket', {
43+
const socketProxy = createProxyMiddleware({
4244
target: 'http://localhost:3000',
45+
pathFilter: '/socket',
4346
ws: true,
4447
});
4548

src/http-proxy-middleware.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,15 @@ export class HttpProxyMiddleware {
116116
* @return {Object} proxy options
117117
*/
118118
private prepareProxyRequest = async (req: Request) => {
119+
/**
120+
* Incorrect usage confirmed: https://github.com/expressjs/express/issues/4854#issuecomment-1066171160
121+
* Temporary restore req.url patch for {@link src/legacy/create-proxy-middleware.ts legacyCreateProxyMiddleware()}
122+
* FIXME: remove this patch in future release
123+
*/
124+
if ((this.middleware as unknown as any).__LEGACY_HTTP_PROXY_MIDDLEWARE__) {
125+
req.url = (req as unknown as any).originalUrl || req.url;
126+
}
127+
119128
const newProxyOptions = Object.assign({}, this.proxyOptions);
120129

121130
// Apply in order:

src/index.ts

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,11 @@ export function createProxyMiddleware(options: Options): RequestHandler {
66
return middleware;
77
}
88

9-
/**
10-
* @deprecated
11-
*/
12-
// export function legacyCreateProxyMiddleware(pathFilter: Filter, options: Options) {
13-
// return createProxyMiddleware({ ...options, pathFilter });
14-
// }
15-
169
export * from './handlers';
1710

1811
export type { Filter, Options, RequestHandler } from './types';
12+
13+
/**
14+
* Legacy exports
15+
*/
16+
export * from './legacy';

src/legacy/create-proxy-middleware.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { createProxyMiddleware } from '..';
2+
import { Debug } from '../debug';
3+
import { Filter, RequestHandler } from '../types';
4+
import { legacyOptionsAdapter } from './options-adapter';
5+
import { LegacyOptions } from './types';
6+
7+
const debug = Debug.extend('legacy-create-proxy-middleware');
8+
9+
/**
10+
* @deprecated
11+
* This function is deprecated and will be removed in a future version.
12+
*
13+
* Use {@link createProxyMiddleware} instead.
14+
*/
15+
export function legacyCreateProxyMiddleware(shortHand: string): RequestHandler;
16+
export function legacyCreateProxyMiddleware(legacyOptions: LegacyOptions): RequestHandler;
17+
export function legacyCreateProxyMiddleware(
18+
legacyContext: Filter,
19+
legacyOptions: LegacyOptions
20+
): RequestHandler;
21+
export function legacyCreateProxyMiddleware(legacyContext, legacyOptions?): RequestHandler {
22+
debug('init');
23+
24+
const options = legacyOptionsAdapter(legacyContext, legacyOptions);
25+
26+
const proxyMiddleware = createProxyMiddleware(options);
27+
28+
// https://github.com/chimurai/http-proxy-middleware/pull/731/files#diff-07e6ad10bda0df091b737caed42767657cd0bd74a01246a1a0b7ab59c0f6e977L118
29+
debug('add marker for patching req.url (old behavior)');
30+
(proxyMiddleware as any).__LEGACY_HTTP_PROXY_MIDDLEWARE__ = true;
31+
32+
return proxyMiddleware;
33+
}

src/legacy/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './public';

0 commit comments

Comments
 (0)