Skip to content

Commit 2bf1f93

Browse files
authored
bug(websocket): fix memory leak when option 'ws:true' is used. (chimurai#114)
1 parent 4db1bfa commit 2bf1f93

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

lib/index.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ module.exports = HttpProxyMiddleware;
1313
function HttpProxyMiddleware(context, opts) {
1414
// https://github.com/chimurai/http-proxy-middleware/issues/57
1515
var wsUpgradeDebounced = _.debounce(handleUpgrade);
16+
var wsInitialized = false;
1617
var config = configFactory.createConfig(context, opts);
1718
var proxyOptions = config.options;
1819

@@ -43,15 +44,24 @@ function HttpProxyMiddleware(context, opts) {
4344
}
4445

4546
if (proxyOptions.ws === true) {
47+
// use initial request to access the server object to subscribe to http upgrade event
4648
catchUpgradeRequest(req.connection.server);
4749
}
4850
}
4951

5052
function catchUpgradeRequest(server) {
51-
server.on('upgrade', wsUpgradeDebounced);
53+
// subscribe once; don't subscribe on every request...
54+
// https://github.com/chimurai/http-proxy-middleware/issues/113
55+
if (!wsInitialized) {
56+
server.on('upgrade', wsUpgradeDebounced);
57+
wsInitialized = true;
58+
}
5259
}
5360

5461
function handleUpgrade(req, socket, head) {
62+
// set to initialized when used externally
63+
wsInitialized = true;
64+
5565
if (shouldProxy(config.context, req)) {
5666
var activeProxyOptions = prepareProxyRequest(req);
5767
proxy.ws(req, socket, head, activeProxyOptions);

0 commit comments

Comments
 (0)