I am trying to create a newsfeed with Node.js, express, and sockets.io.
My problem is that socket.on("connection", function{}); doesn't give you the session id so I have no way of knowing which user is connected. I want to know if there is a way to pass the user id on connection from the session.
I have thought about on connecting the socket from the client side, sending a message to the server immediately after connection with the user id, and the server upon receiving the message with the user id sends back the proper newsfeed items.
I want to know if there is a better/ more scalable/efficient way of doing this.
Thanks a lot.
If you will authorize socket.io request, then you can filter users.
You have to serialize, deserialize user object in order to access properties with socket.io
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
Look at passportSocketIO. You can set authorization to incoming socket.io requests like this.
sio.set("authorization", passportSocketIo.authorize({
key: 'express.sid', //the cookie where express (or connect) stores its session id.
secret: 'my session secret', //the session secret to parse the cookie
store: mySessionStore, //the session store that express uses
fail: function(data, accept) { // *optional* callbacks on success or fail
accept(null, false); // second param takes boolean on whether or not to allow handshake
},
success: function(data, accept) {
accept(null, true);
}
}));
Then you can filter out users in 'connection' callback like this.
sio.sockets.on("connection", function(socket){
console.log("user connected: ", socket.handshake.user.name);
//filter sockets by user...
var userProperty = socket.handshake.user.property, //property
// you can use user's property here.
//filter users with specific property
passportSocketIo.filterSocketsByUser(sio, function (user) {
return user.property=== propertyValue; //filter users with specific property
}).forEach(function(s){
s.send("msg");
});
});