webpack-dev-server: Can't proxy websocket request using proxy option

The webpack-dev-server does not explicitly handle websockets through the proxy option. I would expect an entry like this to correctly proxy websocket requests:

proxy : [{path: /ws, target: ws://localhost:8080/, ws: true}]

After inspecting the Server.js file, it seem that there would need to be explicit handling of websockets. Something like this perhaps:

options.proxy.forEach(function (proxyOptions) {
    app.all(proxyOptions.path, function (req, res) {
        if(typeof proxyOptions.rewrite === 'function') proxyOptions.rewrite(req, proxyOptions);
        if (proxyOptions.host) {
            req.headers.host = proxyOptions.host;
        }
        if (proxyOptions.ws) {
            proxy.ws(req, res, proxyOptions, errorCb.bind(this));
        } else {
            proxy.web(req, res, proxyOptions, errorCb.bind(this));
        }
        function errorCb(err){
            var msg = "cannot proxy to " + proxyOptions.target + " (" + err.message + ")";
            this.io.sockets.emit("proxy-error", [msg]);
            res.statusCode = 502;
            res.end();
        }

        if (proxyOptions.configure) {
            proxyOptions.configure(proxy);
        }
    }.bind(this));
}.bind(this));

or add a new listener for websocket connections:

proxyServer.on('upgrade', function (req, socket, head) {
  proxy.ws(req, socket, head);
});

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 2
  • Comments: 36 (11 by maintainers)

Most upvoted comments

Thanks to @sokra and @SpaceK33z (and perhaps others?) web socket proxying (with socket.io) has been working for at least a couple of weeks now, since resolution #302. This is the config which is working (for me):

I have a socket.io server running on localhost:8001, on path /napi:

var io = require('socket.io')(http, { path: '/napi' })

In webpack config:

devServer: {
        proxy: {
            '/napi/*': {
                target: 'ws://localhost:8001',
                ws: true,
            },
        },
    },

In socket.io client:

var socket = io({ path: '/napi' })

I’m launching with: webpack-dev-server --inline --hot

This has landed in webpack-dev-server 1.15.0.

👍 Lack of websocket proxy support makes using dev-server with “real” backend servers that are based on ws impossible.

@k-makarov proxying for websockets does now work in master, however it looks like there isn’t going to be a new release until webpack 2.0. I created a branch that you can directly npm install from in the meantime here: https://github.com/mjrussell/webpack-dev-server/tree/pre-dist