Manage multiple tabs (but same user) in socket.io

It sounds like you may be referring to the socket id in your question, not the session id. If you have an express session you can use the session id, which will be the same regardless of how many tabs are open as long as they use the same browser and it’s not in “private” mode. Take a look at this question for how to enable sessions in socket.io.

socket.io and session?

Update:
When you’re saving the session id, you’ll associate it with the user’s nickname and the connected sockets. Then you can iterate through each socket and send the message. Something like the following:

[
    {sessionId: '12345', nickname: 'timmay!', socketIds: [1, 2, 3]},
    {sessionId: '23456', nickname: 'pete', socketIds: [4, 5, 6]}
]

When another connection is established you push the new socket id into the socketIds array, and when a user disconnects you remove the id.

Another option might be to only allow one tab per user per session. You can store a single socketId and when a new socket connects for the same user, you can disconnect the original socket and use the new one instead.

Leave a Comment