0

How to get user session with socket.io?

io.sockets.on('connection', function(socket) {
    // Need to get user session
});
Matt
  • 14,007
  • 25
  • 88
  • 136
owl
  • 3,451
  • 2
  • 21
  • 27
  • 1
    possible duplicate of [socket.io and session?](http://stackoverflow.com/questions/4641053/socket-io-and-session) – Ben Fortune Apr 15 '14 at 12:33

1 Answers1

1

You can attach session with socket and get in connection event. Get the user session in authorization, if you're using express then do this:

var sessionStore = new express.session.MemoryStore();
io.set('authorization', function (handshake, accept){
  var cookies = require('express/node_modules/cookie').parse(handshake.headers.cookie);
  var parsed = require('express/node_modules/connect/lib/utils').parseSignedCookies(cookies, 'SESSION_SECRET');
  sessionStore.get(parsed.sid, function (error, session){
    if (session != null && session.user != null){
    accept(null, true);
    handshake.session = session;
    }
  });
});

And in your connection event you can get it like:

socket.handshake.session
M Omayr
  • 1,341
  • 1
  • 9
  • 18