~ read.

Socket.IO + Express 3 sessions

I will try to start blogging sometimes in English, I'm not an expert, but I hope this will let me train it a bit. So please be nice, and don't hesitate to correct me if I make some mistakes... ;-)

I am currently working on a personal project where I use Express 3 and Socket.IO on the backend. Before using the app you MUST login, so all my Express routes are behind an auth middleware. Once the user do a successful login, we set a session flag on Express and he can enter the app and use the other routes. No problems here, it's just some standard Express setup.

Problems came when I decided to use Socket.IO for some real time stuff, as Socket.IO does not care about Express' middlewares. I needed to find a way to only accept a connection to the Socket.IO server if the user was logged by the Express side, and if it was not, we reject the connection.

After some searches (and some really good examples) I've found a way using the Socket.IO authorization. As this is a standard HTTP call, we can get information from it (mainly the cookies and then the Express SID) to check if the user is logged in.

I've setup a complete example with detailed explanations on GitHub : https://github.com/leeroybrun/socketio-express-sessions

Please feel free to comment and let me know what you think.

Don't hesitate to visit the great links provided below, this example is greatly inspired from them.

Sources / initial credits / ideas