Skip to content
Advertisement

Webpack dev server and WebSockets

Three quick questions:

1) Knowing full well the benefits of Socket.io, I still wanna know if it is possible to run a single webpack-dev-server that can server both http and ws. Everything online is oriented to using Socket.io and running dual servers for http / ws.

2) If indeed I must use Socket.io, how does local development (http server and ws server being separate) compare to production environments? Do production environments typically have two servers running for http and ws, or is it usually all one server?

3) If I can use a single webpack-dev-server instance and native WebSockets, how the heck does one configure devServer to serve ws? All online examples are around Socket.io dual server setup so I’ve gotten no where fast.

Thank you!!

Answer

1) webpack-dev-server can only proxy websocket connections, nothing more.

devServer: {
  proxy: {
    '/websocket': {
       target: 'ws://[address]:[port]',
       ws: true // important
    },
  }
}

2) There is no requirement that you should split your server into a HTTP and WS parts. To use both in javascript you can use express-ws. This is also available in other languages (Spring supports it, Django also).

Snippet below serves static files (like webpack-dev-server) along with giving you an websocket interface.

const express = require('express');
const expressWs = require('express-ws');

const app = express();
expressWs(app);

//serve static files, 'public/index.html' will be served as '/'
app.use(express.static('public'));

// normal express.js handler for HTTP GET
app.get('/hello', function(req, res, next){
  res.send('hello');
});

// websocket handler
app.ws('/websocket', function(ws, req) {
  ws.on('message', function(msg) {
    ws.send(msg);
  });
});

app.listen(3000);

3) Again, webpack-dev-server only serves your static files and there is no WS equivalent. You know what to expect when requesting GET /file.txt HTTP 1.1. WS is only a transport protocol.

Bonus: socket.io has generally fallen out of favour since all major browsers now support websockets and there is no need for fallback behaviour.

Advertisement