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

chimurai / http-proxy-middleware / 18263701359

05 Oct 2025 08:07PM UTC coverage: 97.15%. Remained the same
18263701359

push

github

web-flow
ci(ci.yml): unpin node 24 (#1148)

* ci(ci.yml): unpin node 24

* chore(package): reinstall mockttp deps

* build(mockttp): use 2048 bits in generateCACertificate

170 of 183 branches covered (92.9%)

409 of 421 relevant lines covered (97.15%)

24.55 hits per line

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

100.0
/src/http-proxy-middleware.ts
1
import type * as http from 'node:http';
2
import type * as https from 'node:https';
3
import type * as net from 'node:net';
4

5
import * as httpProxy from 'http-proxy';
12✔
6

7
import { verifyConfig } from './configuration';
12✔
8
import { Debug as debug } from './debug';
12✔
9
import { getPlugins } from './get-plugins';
12✔
10
import { getLogger } from './logger';
12✔
11
import { matchPathFilter } from './path-filter';
12✔
12
import * as PathRewriter from './path-rewriter';
12✔
13
import * as Router from './router';
12✔
14
import type { Filter, Logger, Options, RequestHandler } from './types';
15
import { getFunctionName } from './utils/function';
12✔
16

17
export class HttpProxyMiddleware<TReq, TRes> {
12✔
18
  private wsInternalSubscribed = false;
75✔
19
  private serverOnCloseSubscribed = false;
75✔
20
  private proxyOptions: Options<TReq, TRes>;
21
  private proxy: httpProxy<TReq, TRes>;
22
  private pathRewriter;
23
  private logger: Logger;
24

25
  constructor(options: Options<TReq, TRes>) {
26
    verifyConfig<TReq, TRes>(options);
75✔
27
    this.proxyOptions = options;
75✔
28
    this.logger = getLogger(options as unknown as Options);
75✔
29

30
    debug(`create proxy server`);
75✔
31
    this.proxy = httpProxy.createProxyServer({});
75✔
32

33
    this.registerPlugins(this.proxy, this.proxyOptions);
75✔
34

35
    this.pathRewriter = PathRewriter.createPathRewriter(this.proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided
75✔
36

37
    // https://github.com/chimurai/http-proxy-middleware/issues/19
38
    // expose function to upgrade externally
39
    this.middleware.upgrade = (req, socket, head) => {
75✔
40
      if (!this.wsInternalSubscribed) {
3!
41
        this.handleUpgrade(req, socket, head);
3✔
42
      }
43
    };
44
  }
45

46
  // https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript#red-flags-for-this
47
  public middleware: RequestHandler = (async (req, res, next?) => {
75✔
48
    if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
55✔
49
      try {
49✔
50
        const activeProxyOptions = await this.prepareProxyRequest(req);
49✔
51
        debug(`proxy request to target: %O`, activeProxyOptions.target);
48✔
52
        this.proxy.web(req, res, activeProxyOptions);
48✔
53
      } catch (err) {
54
        next?.(err);
2✔
55
      }
56
    } else {
57
      next?.();
6✔
58
    }
59

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

70
    if (server && !this.serverOnCloseSubscribed) {
55✔
71
      server.on('close', () => {
53✔
72
        debug('server close signal received: closing proxy server');
53✔
73
        this.proxy.close();
53✔
74
      });
75
      this.serverOnCloseSubscribed = true;
53✔
76
    }
77

78
    if (this.proxyOptions.ws === true) {
55✔
79
      // use initial request to access the server object to subscribe to http upgrade event
80
      this.catchUpgradeRequest(server);
2✔
81
    }
82
  }) as RequestHandler;
83

84
  private registerPlugins(proxy: httpProxy<TReq, TRes>, options: Options<TReq, TRes>) {
85
    const plugins = getPlugins<TReq, TRes>(options);
75✔
86
    plugins.forEach((plugin) => {
75✔
87
      debug(`register plugin: "${getFunctionName(plugin)}"`);
296✔
88
      plugin(proxy, options);
296✔
89
    });
90
  }
91

92
  private catchUpgradeRequest = (server: https.Server) => {
75✔
93
    if (!this.wsInternalSubscribed) {
2✔
94
      debug('subscribing to server upgrade event');
1✔
95
      server.on('upgrade', this.handleUpgrade);
1✔
96
      // prevent duplicate upgrade handling;
97
      // in case external upgrade is also configured
98
      this.wsInternalSubscribed = true;
1✔
99
    }
100
  };
101

102
  private handleUpgrade = async (req: http.IncomingMessage, socket: net.Socket, head: Buffer) => {
75✔
103
    try {
4✔
104
      if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
4!
105
        const activeProxyOptions = await this.prepareProxyRequest(req);
4✔
106
        this.proxy.ws(req, socket, head, activeProxyOptions);
3✔
107
        debug('server upgrade event received. Proxying WebSocket');
3✔
108
      }
109
    } catch (err) {
110
      // This error does not include the URL as the fourth argument as we won't
111
      // have the URL if `this.prepareProxyRequest` throws an error.
112
      this.proxy.emit('error', err, req, socket);
1✔
113
    }
114
  };
115

116
  /**
117
   * Determine whether request should be proxied.
118
   */
119
  private shouldProxy = (
75✔
120
    pathFilter: Filter<TReq> | undefined,
121
    req: http.IncomingMessage,
122
  ): boolean => {
123
    try {
59✔
124
      return matchPathFilter(pathFilter, req.url, req);
59✔
125
    } catch (err) {
126
      debug('Error: matchPathFilter() called with request url: ', `"${req.url}"`);
1✔
127
      this.logger.error(err);
1✔
128
      return false;
1✔
129
    }
130
  };
131

132
  /**
133
   * Apply option.router and option.pathRewrite
134
   * Order matters:
135
   *    Router uses original path for routing;
136
   *    NOT the modified path, after it has been rewritten by pathRewrite
137
   * @param {Object} req
138
   * @return {Object} proxy options
139
   */
140
  private prepareProxyRequest = async (req: http.IncomingMessage) => {
75✔
141
    /**
142
     * Incorrect usage confirmed: https://github.com/expressjs/express/issues/4854#issuecomment-1066171160
143
     * Temporary restore req.url patch for {@link src/legacy/create-proxy-middleware.ts legacyCreateProxyMiddleware()}
144
     * FIXME: remove this patch in future release
145
     */
146
    if ((this.middleware as unknown as any).__LEGACY_HTTP_PROXY_MIDDLEWARE__) {
53✔
147
      req.url = (req as unknown as any).originalUrl || req.url;
5!
148
    }
149

150
    const newProxyOptions = Object.assign({}, this.proxyOptions);
53✔
151

152
    // Apply in order:
153
    // 1. option.router
154
    // 2. option.pathRewrite
155
    await this.applyRouter(req, newProxyOptions);
53✔
156
    await this.applyPathRewrite(req, this.pathRewriter);
51✔
157

158
    return newProxyOptions;
51✔
159
  };
160

161
  // Modify option.target when router present.
162
  private applyRouter = async (req: http.IncomingMessage, options: Options<TReq, TRes>) => {
75✔
163
    let newTarget;
164

165
    if (options.router) {
53✔
166
      newTarget = await Router.getTarget(req, options);
13✔
167

168
      if (newTarget) {
11✔
169
        debug('router new target: "%s"', newTarget);
9✔
170
        options.target = newTarget;
9✔
171
      }
172
    }
173
  };
174

175
  // rewrite path
176
  private applyPathRewrite = async (req: http.IncomingMessage, pathRewriter) => {
75✔
177
    if (pathRewriter) {
51✔
178
      const path = await pathRewriter(req.url, req);
10✔
179

180
      if (typeof path === 'string') {
10✔
181
        debug('pathRewrite new path: %s', req.url);
9✔
182
        req.url = path;
9✔
183
      } else {
184
        debug('pathRewrite: no rewritten path found: %s', req.url);
1✔
185
      }
186
    }
187
  };
188
}
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