How to access session ID when using Socket.IO?

I have a chat and I need to manage unique connections. I searched, but the solutions I found seem outdated.

So how do I get the socket session id with Socket.IO?

I use Node.js , Express.js and Socket.IO .

+7
javascript express
source share
1 answer

Use the Socket.IO check parameter and pass cookies to the cookie parser middleware from Express. After analyzing the cookie, you can get the client session identifier and retrieve the associated session from the session store, whether it is a memory history or other type of store.

// we need to use the same secret for Socket.IO and Express var parseCookie = express.cookieParser(secret); var store = /* your MemoryStore, RedisStore, etc */; io.set('authorization', function(handshake, callback) { if (handshake.headers.cookie) { // pass a req, res, and next as if it were middleware parseCookie(handshake, null, function(err) { handshake.sessionID = handshake.signedCookies['connect.sid']; // or if you don't have signed cookies handshake.sessionID = handshake.cookies['connect.sid']; store.get(handshake.sessionID, function (err, session) { if (err || !session) { // if we cannot grab a session, turn down the connection callback('Session not found.', false); } else { // save the session data and accept the connection handshake.session = session; callback(null, true); } }); }); } else { return callback('No session.', false); } callback(null, true); }); 

Each time the client tries to connect, the authorization function starts. It takes the handshake header cookies ( handshake.headers.cookies ) and passes them to express.cookieParser() . The cookie parser then finds the session identifier, and then searches for the store for the associated session. Then we store the linked session in handshake.session , so we can access it as follows:

 app.get('/', function(req, res) { req.session.property = 'a value'; }); io.sockets.on('connection', function(socket) { var session = socket.handshake.session; session.property // a value }); 
+10
source share

All Articles