I\'m using the express framework, and part of my web app uses socket.io to enable real-time chat. I need to get the current user\'s username, and create a room with him in it. T
This has been asked a few times but the older answers I found do not work anymore. The answer lies in parsing socket.handshake.headers.cookie
but this is hacky and will depend on the internals of express-session
.
Anyways, this should work for now with Express 4 and socket.io 1.1:
var express = require('express'),
session = require('express-session'),
cookie = require('cookie'),
signature = require('cookie-signature');
var app = express(),
store = new session.MemoryStore(),
secret = 'session-secret-key',
name = 'connect.sid';
app.use(session({
name: name,
secret: secret,
store: store,
resave: true,
saveUninitialized: true
}));
var server = require('http').createServer(app),
io = require('socket.io')(server);
io.on('connection', function(socket) {
if (socket.handshake && socket.handshake.headers && socket.handshake.headers.cookie) {
var raw = cookie.parse(socket.handshake.headers.cookie)[name];
if (raw) {
// The cookie set by express-session begins with s: which indicates it
// is a signed cookie. Remove the two characters before unsigning.
socket.sessionId = signature.unsign(raw.slice(2), secret) || undefined;
}
}
if (socket.sessionId) {
store.get(socket.sessionId, function(err, session) {
console.log(session);
});
}
});