• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

chimurai / http-proxy-middleware / 4358068220

pending completion
4358068220

push

github

chimurai
refactor: minor type improvements

161 of 166 branches covered (96.99%)

6 of 6 new or added lines in 2 files covered. (100.0%)

368 of 376 relevant lines covered (97.87%)

24.37 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

99.01
/src/http-proxy-middleware.ts
1
import type * as http from 'http';
2
import type * as https from 'https';
3
import type { RequestHandler, Options, Filter } from './types';
4
import * as httpProxy from 'http-proxy';
12✔
5
import { verifyConfig } from './configuration';
12✔
6
import { getPlugins } from './get-plugins';
12✔
7
import { matchPathFilter } from './path-filter';
12✔
8
import * as PathRewriter from './path-rewriter';
12✔
9
import * as Router from './router';
12✔
10
import { Debug as debug } from './debug';
12✔
11
import { getFunctionName } from './utils/function';
12✔
12

13
export class HttpProxyMiddleware<TReq, TRes> {
12✔
14
  private wsInternalSubscribed = false;
70✔
15
  private serverOnCloseSubscribed = false;
70✔
16
  private proxyOptions: Options<TReq, TRes>;
17
  private proxy: httpProxy<TReq, TRes>;
18
  private pathRewriter;
19

20
  constructor(options: Options<TReq, TRes>) {
21
    verifyConfig<TReq, TRes>(options);
70✔
22
    this.proxyOptions = options;
70✔
23

24
    debug(`create proxy server`);
70✔
25
    this.proxy = httpProxy.createProxyServer({});
70✔
26

27
    this.registerPlugins(this.proxy, this.proxyOptions);
70✔
28

29
    this.pathRewriter = PathRewriter.createPathRewriter(this.proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided
70✔
30

31
    // https://github.com/chimurai/http-proxy-middleware/issues/19
32
    // expose function to upgrade externally
33
    this.middleware.upgrade = (req, socket, head) => {
70✔
34
      if (!this.wsInternalSubscribed) {
2✔
35
        this.handleUpgrade(req, socket, head);
2✔
36
      }
37
    };
38
  }
39

40
  // https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript#red-flags-for-this
41
  public middleware: RequestHandler = (async (req, res, next?) => {
70✔
42
    if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
53✔
43
      try {
48✔
44
        const activeProxyOptions = await this.prepareProxyRequest(req);
48✔
45
        debug(`proxy request to target: %O`, activeProxyOptions.target);
47✔
46
        this.proxy.web(req, res, activeProxyOptions);
47✔
47
      } catch (err) {
48
        next && next(err);
2✔
49
      }
50
    } else {
51
      next && next();
5✔
52
    }
53

54
    /**
55
     * Get the server object to subscribe to server events;
56
     * 'upgrade' for websocket and 'close' for graceful shutdown
57
     *
58
     * NOTE:
59
     * req.socket: node >= 13
60
     * req.connection: node < 13 (Remove this when node 12/13 support is dropped)
61
     */
62
    const server: https.Server = ((req.socket ?? req.connection) as any)?.server;
53✔
63

64
    if (server && !this.serverOnCloseSubscribed) {
53✔
65
      server.on('close', () => {
51✔
66
        debug('server close signal received: closing proxy server');
51✔
67
        this.proxy.close();
51✔
68
      });
69
      this.serverOnCloseSubscribed = true;
51✔
70
    }
71

72
    if (this.proxyOptions.ws === true) {
53✔
73
      // use initial request to access the server object to subscribe to http upgrade event
74
      this.catchUpgradeRequest(server);
2✔
75
    }
76
  }) as RequestHandler;
77

78
  private registerPlugins(proxy: httpProxy<TReq, TRes>, options: Options<TReq, TRes>) {
79
    const plugins = getPlugins<TReq, TRes>(options);
70✔
80
    plugins.forEach((plugin) => {
70✔
81
      debug(`register plugin: "${getFunctionName(plugin)}"`);
277✔
82
      plugin(proxy, options);
277✔
83
    });
84
  }
85

86
  private catchUpgradeRequest = (server: https.Server) => {
70✔
87
    if (!this.wsInternalSubscribed) {
2✔
88
      debug('subscribing to server upgrade event');
1✔
89
      server.on('upgrade', this.handleUpgrade);
1✔
90
      // prevent duplicate upgrade handling;
91
      // in case external upgrade is also configured
92
      this.wsInternalSubscribed = true;
1✔
93
    }
94
  };
95

96
  private handleUpgrade = async (req: http.IncomingMessage, socket, head) => {
70✔
97
    if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
3✔
98
      const activeProxyOptions = await this.prepareProxyRequest(req);
3✔
99
      this.proxy.ws(req, socket, head, activeProxyOptions);
3✔
100
      debug('server upgrade event received. Proxying WebSocket');
3✔
101
    }
102
  };
103

104
  /**
105
   * Determine whether request should be proxied.
106
   */
107
  private shouldProxy = (
70✔
108
    pathFilter: Filter<TReq> | undefined,
109
    req: http.IncomingMessage
110
  ): boolean => {
111
    return matchPathFilter(pathFilter, req.url, req);
56✔
112
  };
113

114
  /**
115
   * Apply option.router and option.pathRewrite
116
   * Order matters:
117
   *    Router uses original path for routing;
118
   *    NOT the modified path, after it has been rewritten by pathRewrite
119
   * @param {Object} req
120
   * @return {Object} proxy options
121
   */
122
  private prepareProxyRequest = async (req: http.IncomingMessage) => {
70✔
123
    /**
124
     * Incorrect usage confirmed: https://github.com/expressjs/express/issues/4854#issuecomment-1066171160
125
     * Temporary restore req.url patch for {@link src/legacy/create-proxy-middleware.ts legacyCreateProxyMiddleware()}
126
     * FIXME: remove this patch in future release
127
     */
128
    if ((this.middleware as unknown as any).__LEGACY_HTTP_PROXY_MIDDLEWARE__) {
51✔
129
      req.url = (req as unknown as any).originalUrl || req.url;
5!
130
    }
131

132
    const newProxyOptions = Object.assign({}, this.proxyOptions);
51✔
133

134
    // Apply in order:
135
    // 1. option.router
136
    // 2. option.pathRewrite
137
    await this.applyRouter(req, newProxyOptions);
51✔
138
    await this.applyPathRewrite(req, this.pathRewriter);
50✔
139

140
    return newProxyOptions;
50✔
141
  };
142

143
  // Modify option.target when router present.
144
  private applyRouter = async (req: http.IncomingMessage, options) => {
70✔
145
    let newTarget;
146

147
    if (options.router) {
51✔
148
      newTarget = await Router.getTarget(req, options);
10✔
149

150
      if (newTarget) {
9✔
151
        debug('router new target: "%s"', newTarget);
7✔
152
        options.target = newTarget;
7✔
153
      }
154
    }
155
  };
156

157
  // rewrite path
158
  private applyPathRewrite = async (req: http.IncomingMessage, pathRewriter) => {
70✔
159
    if (pathRewriter) {
50✔
160
      const path = await pathRewriter(req.url, req);
10✔
161

162
      if (typeof path === 'string') {
10✔
163
        debug('pathRewrite new path: %s', req.url);
9✔
164
        req.url = path;
9✔
165
      } else {
166
        debug('pathRewrite: no rewritten path found: %s', req.url);
1✔
167
      }
168
    }
169
  };
170
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc