0

I'm trying to create an multi-user and multi-permission system that uses socket.io in order to make a lot of the features real-time and fluid.

I have everything setup and functionally working on page load, querying databases and pulling through relevant data based on the user, their permissions and what groups they're a part of however how would I go about assigning this user a socket, that retains this 'user info' such as their used id along with other things you'd commonly find within session data?

From what I can see, the socket ID resets and changes whenever a page is loaded, refreshed or closed so I can't store this ID in the database temporarily against the user to query against - I'm a little stuck on the best way / practice to go about this.

Edit: I should mention that my application is already built and fully functional aside from the socket side of things using Express.

Josh Walshaw
  • 200
  • 1
  • 2
  • 17
  • Look into FeathersJS. I believe it has everything you need built into an easy to use back-end framework. If you're not looking to use a framework, you may be able to setup channels in socket.io based on the users database id. That might be a pain to implement, so I would suggest taking a look at FeathersJS. – Jayson H Jul 24 '17 at 20:50

1 Answers1

0

Your are correct that every new page the user navigates to will close the prior socket.io connection and create a new one and each new socket.io connection will have a new socket.id. The socket.id is not meant to be used as a persistent reference to a specific user. It is only a reference to a specific connection.

Instead, what it sounds like you want is some sort of user session that you can persistently identify the user every time there's a new socket.io connection. You would then use your own userID as a persistent id that can apply to each incoming socket.io connection.

The usual scheme here is to set up a regular http session using something like express-session and/or passport. Once you have that, you have a means of identifying all incoming http connections as to what user they belong to. Since every socket.io connection starts as an http request, that means you can identify all socket.io connections to. To do that, you can either use both express-session and express-socket.io-session to do most of the work for you or you can set things up yourself as described here: How to share sessions with Socket.IO 1.x and Express 4.x?

jfriend00
  • 683,504
  • 96
  • 985
  • 979