How to use passport with express and socket.io?

Here is a solution using Socket.IO 1.0 and Express 4.0. It is similar in spirit to Patrick’s answer. The trick is that since Socket.IO 1.0 has a new middleware API, we can wrap Express’s middleware and put it into the Socket.IO pipeline without delving into the low-level implementation of the session stores.

// Set up the Session middleware using a MongoDB session store
expressSession = require("express-session");
var sessionMiddleware = expressSession({
    name: "COOKIE_NAME_HERE",
    secret: "COOKIE_SECRET_HERE",
    store: new (require("connect-mongo")(expressSession))({
        url: "mongodb://localhost/DATABASE_NAME_HERE"
    })
});

// Set up the Express server
var app = require("express")()
    .use(sessionMiddleware)
    .use(passport.initialize())
    .use(passport.session())
    // ... more middleware ...
    .listen(8000);

// Set up the Socket.IO server
var io = require("socket.io")(app)
    .use(function(socket, next){
        // Wrap the express middleware
        sessionMiddleware(socket.request, {}, next);
    })
    .on("connection", function(socket){
        var userId = socket.request.session.passport.user;
        console.log("Your User ID is", userId);
    });

The variable sessionMiddleware is a function that is designed to fit directly into the Express pipeline. It takes exactly three arguments: the request object, the response object, and a callback.

Socket.IO’s pipeline expects its middleware to take only two arguments, however: the socket object (which contains the request object at socket.request) and a callback. Luckily sessionMiddleware does not require the response object to read the session from the store, so we simply pass it an empty object as the second argument.

Note that some comments below observe that this code renders the session read-only. This is the functionality we lose by not having a proper response object with Socket.IO.

In the above example I use a MongoDB session store (connect-mongo). You can use whatever session store fits your liking. Refer to the Connect wiki for a list of session stores.

Leave a Comment