Here’s my solution for the following environment:
- express 4.2.0
- socket.io 1.1.0
- cookie-parser 1.0.1
- cookie-session 1.0.2
Code:
var cookieParser = require('cookie-parser')();
var session = require('cookie-session')({ secret: 'secret' };
...
app.use(cookieParser);
app.use(session);
...
io.use(function(socket, next) {
var req = socket.handshake;
var res = {};
cookieParser(req, res, function(err) {
if (err) return next(err);
session(req, res, next);
});
});
Then you can access the session from the socket’s handshake:
io.on('connection', function (socket) {
console.log("Session: ", socket.handshake.session);
});
For people wondering how/why this works:
- We send the
handshake
request through the cookie parser so that cookies are available - Then we send the
handshake
through session middleware as if its a normal request - The middleware attaches
session
to the request - We use
handshake
because for all intents and purposes, it is a normal request, and the parser and session middleware can deal with it properly. This is why you must access thesession
through thehandshake