express.use(path, proxy()) ignores path for websockets

Author: ftesCreated Sep 27, 2017Updated May 14, 2025

Also see expressjs/express#3428.

Expected behavior

The following should listen for websocket requests only under /__webpack_hmr.

javascript
express.use('/__webpack_hmr', proxy({ ws: true, target: 'http://...' }));

Websocket requests to other paths (e.g. /socket.io) should not be handled by the proxy.

Actual behavior

The proxy "hijacks" all incoming websocket requests, also those to /socket.io (see socketio/socket.io#3062).

Setup

Fiddle: https://github.com/ftes/socket.io-fiddle/pull/1/files

  • http-proxy-middleware: 0.17.4
  • server: express 4.13.4
  • socket.io: 2.0.3

proxy middleware configuration

javascript
proxy({ ws: true, target: 'http://localhost:4000' });

server mounting

javascript
var app = express();

app.use('/__webpack_hmr', proxy);
app.listen(3000);

Workaround

Pass path /__webpack_hmr as context to proxy.

javascript
const webpackHmrProxy = proxy('/__webpack_hmr', {
  target: 'http://localhost:4000',
  ws: true,
});
app.use(webpackHmrProxy);

Source: chimurai/http-proxy-middleware