1

Excuse my ignorance, day 2 of node.js/socket.io

I'm looking for a way to uniquely identify users for use in a database queuing system. I read a lot about using Express's session cookie, however I've noticed socket.id seems to be an UID that socket.io is already using.

Therefore I have been using socket.id to identify my users both in the database, and in creating private "rooms" to communicate with just them.

Is this a terrible idea?

1
  • The big question for me is, will this be unique among multiple instances running at the same time?
    – kroe
    Jun 24, 2015 at 18:38

2 Answers 2

7

A socket ID is just that - it uniquely identifies a socket. It doesn't uniquely identify a user, and it's definitely not intended to be used for that purpose. A single user (in many applications) might have multiple connections (and therefore multiple sockets with different ID's). Also, every time they connect they will be assigned a new ID.

So you obviously shouldn't use a socket.id as a user ID. Mustafa points out that you could reassign socket.id to a user ID, but I tend to think that's a very bad idea for two reasons:

  1. socket.id is supposed to uniquely identify a socket, so you would run into problems when a single user has multiple sockets open.
  2. Socket.IO, uses that ID internally a lot for storing things in hashtables, and if you change the ID, you might get unexpected results and hard to track down bugs. I haven't tested it, but looking at the Socket.IO source, that's what I would expect.

Better to generate ID's using another method then associate a user with a socket (for example, during the handshake using data from the cookie).

socket.set(key, value, callback) is the method explicitly intended to be used for associating your own data (like a user ID) with a socket connection, and is the only one guaranteed to be safe.

1
  • Thank you for this information! The multiple tab/session isn't an issue for the problem I am solving, so it's good to hear I can use this for that purpose. However I will look to use cookies if such a need to identify/persist multiple sessions presents itself.
    – Titan
    Apr 14, 2013 at 20:26
1

When the socket.io sockets are created, you can add variables as you wish to socket object. socket.userid = getUserID() will work fine. It is better to make assinging UIDs in database, and add them to socket objects when their authentication is succesful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.