15

I have a similar issue to a previous question (Adding data to a socket.io socket object). I am using socket.io 1.3.4 and would like to add additional data to a socket when it connects. Socket.io used to have a method called set which allowed for this, but it seems to longer work. Is there a new way to do this now?

2
  • 1
    The socket object is a javascript object. You can just add your own custom properties to it. socket.myProp = "foo";. Commented Apr 20, 2015 at 2:12
  • 1
    This approach wont work if you're using TypeScript. Commented Jun 10, 2020 at 18:12

2 Answers 2

9

The correct way to do it as of v4 is to use data property:

this.ioServer.on('connection', async (socket) => {
  const user: IUser = socket.handshake.auth.user
  socket.data.user = user
  ...
Sign up to request clarification or add additional context in comments.

1 Comment

socket.data.user = {fname:'John',lname:'Doe'}; works really great on v4. Thank you.
8

These get/set methods appear to have been removed for 1.0:

http://socket.io/blog/introducing-socket-io-1-0/#scalability

I think the new practice is to simply set properties on the socket object directly as suggested in the question you linked.

You can see an example of this in socket.io's chat example:

https://github.com/Automattic/socket.io/blob/318d62/examples/chat/index.js#L36

3 Comments

Sorry I forgot to mention. I want to add these sockets into 'rooms' which will go over a few machines. This method seems to add a global list, but will this global list be able to be accessed by other machines? As well, as the solution posted in the question I posted, would this way of saving socket object data cause naming conflicts?
Oh I see. The option of using get/set to synchronize state across nodes was also removed with 1.0: socket.io/blog/introducing-socket-io-1-0/#scalability If you want to persist some shared state across nodes it should be simple enough to do it directly with redis.
Yes I looked at this feature, but I would really like to avoid any additional databases for this feature if I can.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.