Anand Singh
Anand Singh

Reputation: 2363

How to access session in socket(Node.js)

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.

Upvotes: 0

Views: 1652

Answers (1)

Anand Singh
Anand Singh

Reputation: 2363

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

Upvotes: 1

Related Questions