WebSocket endpoints for Express applications. Lets you define WebSocket endpoints like any other type of route, and applies regular Express middleware. The WebSocket support is implemented with the help of the ws library.
npm install --save express-ws
Full documentation can be found in the API section below. This section only shows a brief example.
Add this line to your Express application:
var expressWs = app;
Now you will be able to add WebSocket routes (almost) the same way you add other routes. The following snippet sets up a simple echo server at
ws parameter is an instance of the WebSocket class described here.
It works with routers, too, this time at
var router = express;router;app;
var express = ;var app = ;var expressWs = app;app;app;app;app;
express-ws on the specified
app. This will modify the global Router prototype for Express as well - see the
leaveRouterUntouched option for more information on disabling this.
http.Server, you should pass it in here, so that
express-wscan use it to set up the WebSocket upgrade handlers. If you don't specify a
server, you will only be able to use it with the server that is created automatically when you call
express-wsfrom modifying the Router prototype. You will have to manually
applyToevery Router that you wish to make
.wsavailable on, when this is enabled.
This function will return a new
express-ws API object, which will be referred to as
wsInstance in the rest of the documentation.
This property contains the
express-ws was set up on.
Returns the underlying WebSocket server/handler. You can use
wsInstance.getWss().clients to obtain a list of all the connected WebSocket clients for this server.
Note that this list will include all clients, not just those for a specific route - this means that it's often not a good idea to use this for broadcasts, for example.
express-ws on the given
router (or other Router-like object). You will only need this in two scenarios:
In most cases, you won't need this at all.
This module is written in ES6, and uses Babel for compilation. What this means in practice:
npm run buildto compile it.