0

I am using express and socket.io for developing a random chat application.Now i need to access session in socket event.

io.sockets.on('connection', function(socket){  
  socket.on('sendMessage',function(data){
   session.userId //senderId
 }); 
});

session is available in request object but is there is easy way to access session in socket events.I have checked these questions but the answers are quite complicated and old.

How to share sessions with Socket.IO 1.x and Express 4.x?

socket.io and session?

How to get session id with Socket.IO?

please share if any new way is there.

Community
  • 1
  • 1
Anand Singh
  • 2,343
  • 1
  • 22
  • 34

1 Answers1

1

I found a simple way for this..
If you're using socket.io >= 1.0 here is a simple module

var ios = require('socket.io-express-session');
var io = require("socket.io")(server);
io.use(ios(Session));

then

var sess = socket.handshake.session;
sess.userId

As simple as that.

reference session.socket.io

Anand Singh
  • 2,343
  • 1
  • 22
  • 34