How to correctly setup devServer for WebSocket proxying in a vue-cli app

Viewed 2730

I have a Node.JS server running at http://localhost:8080 with 2 routes:

  • "/": Serves /public/index.html.
  • "/rest": Returns { ok: true }.

This server is also running a Websocket connection on the same port. Inside index.html I connect to the server with const socket = new WebSocket("ws://" + window.location.host).

When I run this server and visit http://localhost:8080 the following works:

  • Index is served: Yes ✅
  • The JSON is returned: Yes ✅
  • WebSocket messaging: Yes ✅

Additionally, I am also running a vue-cli app at http://localhost:8079 in development mode with the following vue.config.js configuration:

...
devServer: {
  port: 8079,
  "/": {
    target: "http://localhost:8080/",
    ws: true
  },
}

When I run this app and visit http://localhost:8079 the following happens:

  • Index is served: Yes ✅, it means the proxy is working for this route.
  • The JSON is returned: Yes ✅, it means the proxy is working for this route.
  • WebSockets messaging: No ❌, I get the error "WebSocket connection to 'ws://localhost:8079/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED"

What I am doing wrong? How can I fix it?

As you can see I have included ws: true which is used to proxy WebSocket connections as well.

1 Answers

I have the following in the vue.config.js:

  devServer: {
    proxy: {
      '^/': {
        target: 'http://localhost:8089',
        ws: true,
        changeOrigin: true
      }
    }
  }

The websocket backend runs on port 8089. All ws traffic proxied to the backend.

Related