Support Multiple Connections Per User
A real user may connect through multiple devices or browser tabs.
For example, the same user might be connected through:
- A desktop browser.
- A mobile browser.
- A second desktop tab.
Maintaining only one socket ID per user means a new connection can overwrite an existing connection.
A better approach is to use a user-specific room.
When an authenticated user connects, join a room named using their permanent user ID.
For example:
user:12345
Now all connections belonging to that user can receive the same private notification.
io.on('connection', async (socket) => {
const userId = socket.data.userId;
if (!userId) return;
await socket.join(`user:${userId}`);
console.log(`User ${userId} connected`);
});
function sendPrivateNotification(io, userId, notification) {
io.to(`user:${userId}`).emit('notification:new', notification);
}All sockets belonging to the same authenticated user join a shared user-specific room. Sending an event to that room reaches all active connections belonging to the user.
A single user can have multiple active sockets.
User-specific rooms simplify multi-device messaging.
Use stable authenticated user IDs rather than socket IDs.