MEAN application, getting all sockets during a request


In my MEAN application I had a need to get the list of all open websockets during a particular request. Turns out with this is easily doable if can save a reference to the socketio variable during initialization.

For a typical init in Express, the app.js would contain the following code:

var app = express();
var socketio = require('')(server, {
    path: '/'

So what you need to do is save a reference to the “socketio” variable, which can be retrieved from the request passed down in Express, and used to get all sockets. To do so, you can set it as an application-wide variable in Express like so in app.js:

app.set('socketio', socketio);

Next, a typical Express function handling a request looks like so:

function(req, res) {

From your request (the “req” variable) you can get a reference to the Express app, which allows you to get a reference to the socketio variable you set application wide, which you can use to get the list of sockets. Like so:

function(req, res)  {
    var sockets ='socketio').sockets.sockets;

And now you can loop through all the sockets like below, and do whatever with them you’d like:

for (var socketId in sockets) {
    var socket = sockets[socketId];

As easy as that!

Leave a Reply