express, sessions, authentication and socket.io?

2,368 views
Skip to first unread message

Shripad K

unread,
Oct 11, 2010, 11:19:02 AM10/11/10
to sock...@googlegroups.com
How do i access the req.session in socket.io?
I tried client.request.session, but it returns undefined!

     var io = require(__dirname + '/lib/support/socket.io-node/index.js');

     //configuration

     // routes

     // boot
var io = io.listen(app);

io.on('connection', function(client){

client.on('connect', function() {
client.broadcast({ announcement: client.request.session.name + ' connected' });
});

client.on('message', function(msg){
var msg = { message: [msg.name, msg.message] };
client.broadcast(msg);
});

client.on('disconnect', function(){
client.broadcast({ announcement: client.request.session.name + ' Disconnected' });
});

});

Message has been deleted

Arnout Kazemier

unread,
Oct 11, 2010, 1:00:30 PM10/11/10
to sock...@googlegroups.com
You cant, socket.io put's it self above any other request handler you are using. So your "req" will not be parsed by connect.
Unless you manually modify the listener.js to stop putting socket.io on top. 

Guillermo Rauch

unread,
Oct 11, 2010, 1:21:36 PM10/11/10
to sock...@googlegroups.com

Shripad K

unread,
Oct 11, 2010, 2:05:18 PM10/11/10
to sock...@googlegroups.com
awesome! thanks Guillermo! :)

Shripad K

unread,
Oct 13, 2010, 1:58:55 PM10/13/10
to sock...@googlegroups.com
Guillermo, the option existed in socket.io all this while. Just poked around the source and found out that the session data was stored in `client.listener.server.viewHelpers` ala express(connect) based viewHelpers. I don't suppose creating a new layer on top of socket.io for session support is required now. :)

All you have to do is:
io.on('connection', function(client) {
      var session_data = client.listener.server.viewHelpers;
      console.log(session_data);
      .
      .
      .
});

Shripad

Shripad K

unread,
Oct 13, 2010, 2:04:41 PM10/13/10
to sock...@googlegroups.com
You just need to store the session data in the express dynamicHelpers. Example:

app.dynamicHelpers({
current_user: function(req) {
return req.session.user;
}
});

And its available to client.listener.server.viewHelpers
:)

killfill

unread,
May 20, 2011, 3:15:24 PM5/20/11
to sock...@googlegroups.com
Hello all,

I need to access the session data of req.session too, and i found this post.

I can see that client.listener.server.viewHelpers contains the functions defined in app.dynamicHelpers just fine.

How do i acces them?.

For example, this will fail becouse req is not defined:

io.on('connection', function(client) {
      var session_data = client.listener.server.viewHelpers.current_user();
});


Thanks in advance!

Shripad K

unread,
May 20, 2011, 10:51:37 PM5/20/11
to sock...@googlegroups.com
I sincerely apologize for providing this solution. Please don't use this. It results in race conditions.

Reply all
Reply to author
Forward
0 new messages