Koa.js and Socket.io

I have been working with a project in Koa.js that is a small framework for node.js and yesterday I wanted to add Socket.io to it but run in to some problems. I couldn’t figure out how to use socket.io with Koa.js and after a lot of googling I found some Japanese project on github that solved my problem.

My problem was that I wanted to get koa-router, koa-views, jade and everything working but I didn’t get everything to work together. It turned out to be a quite simple solution to my problem, all I had to do was initialize socket.io after the last app.use().

Here is an example with Koa.js, koa-(router, views, static), jade and socket.io:

var app = require('koa')(),
    router = require('koa-router'),
    serve = require('koa-static'),
    views = require('koa-views');

// Send static files
app.use(serve('./public'));

// Use jade
app.use(views(__dirname +'/views', 'jade', {}));

// Router
app.use(router(app));

// This must come after last app.use()
var server = require('http').Server(app.callback()),
    io = require('socket.io')(server);

/**
 * Routes can go both before and after but
 * app.use(router(app)); must be before
 */
app.get('/', function *(next) {
  yield this.render('index', { my: 'data' });
});

// Socket.io
io.on('connection', function(socket){
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

// Start the server
server.listen(1337);
console.info('Now running on localhost:1337');

I hope this article could be to any help.

3 responses to “Koa.js and Socket.io”

  1. sam says:

    looks like u are first on the spot! thanks for paving the way.

  2. Cohars says:

    Hey, thanks for this article. Can you explain we the server and io must come after the last app.use()?

    I was stuck on it and I don’t get the point of it. Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *