facebookinstagrammailtwitter

verwebbt

socket.io in an express app

Socket.io’s Documentation on how to use it with expressjs is slightly not-so-useful. Most likely you will have some MVCish pattern and your controller is far away from where your app lives. I guess you are using express.Router() (at least you should), making it even more difficult to pass the socket.io instance through some require calls. A solution to this occurred to me in the shower.

For simplifying things I wrote this in one file.

var http = require('http')
  , express = require('express')
  , socketio = require('socket.io');
var app = express()
  , sio = socketio();

/**
 * Middleware
 */
// This attaches the socket.io instance
// to the request object
app.use(function(req, res, next) {
  req.io = sio; next();
});

// More middleware, like the following
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, './public')));

/**
 * Router
 */
app.get('/', function(req, res) {
  req.io.sockets.emit('hi', { hello: 'world' });
  res.send('Hello World');
});

/**
 * Server creation
 */
var server = http.createServer(app);
server.listen(3000);
sio.listen(server);