Quick Tip: Node.js + Socket.io + Authentication
Introduction
This is an incredibly quick tip that might save you a ton of time. I hope this tip receives you well.
Problem
Socket.IO does not have access to session information, therefore the server has no way of linking a message it receives to a specific user.
Solution
If you are running into this situation the solution is to use cookies. When you authenticate your user in your main application, create a cookie with the information you’d like socket to know. The user ID is a good start. Then send the cookie to the client. In express you can do this with res.cookie(key, value); . Then you can pull in this information with javascript on the client-side using document.cookie. Now the client has a userID that he can pass within a socket.io message to the server for the remainder of the session. I sincerely believe this is the only way. I’m pretty sure I’ve tried every iteration possible, leading to all sorts of race conditions. I dare you to come up with another solution
. As always, feedback is appreciated!

Comments
Dan
Thursday, January 20th, 2011
Matt Mueller
Saturday, January 22nd, 2011
Sam Lown • http://www.samlown.com
Thursday, August 4th, 2011
Andreas • http://www.andreasklostermann.de/
Monday, December 19th, 2011