How to sync state across multiple user devices?
multi-device presence and state coherence patterns.
attach userId to each socket, track active sockets per user, broadcast user state to all their sockets.
THE MULTI-DEVICE PROBLEM
When a user opens your app on a phone and laptop, the server sees two separate WebSocket connections. If the user clicks a button on the phone, only the phone socket receives the response. The laptop socket is unaware, showing stale state. Without explicit synchronization, the devices diverge.
SOCKET-TO-USER MAPPING
Maintain a mapping of userId to all connected sockets. In the connection handler, extract userId from the JWT, then add the socket to a collection: usersWithSockets[userId] = usersWithSockets[userId] || []; usersWithSockets[userId].push(socket.id);. On disconnect, remove the socket from the list. This allows you to broadcast to all of a user's connections.
CENTRAL STATE STORE
For important state (user settings, document edits, presence status), store in a database or cache (Redis). When a user changes something on the phone, write to the store, then emit the updated state to all their sockets. This ensures both devices see the change. For example: user clicks settings on phone, server writes to database, server emits 'settingsUpdated' to all sockets of that user, laptop updates its UI.
BROADCAST TO ALL USER SOCKETS
Create a helper: io.to() sends to a single room. To send to all sockets of a user, join each socket to a user room on connect: socket.join('user:' + userId);. Then broadcast: io.to('user:' + userId).emit('stateChange', newState);. Both devices receive simultaneously.
EVENT DEDUPLICATION
When a user's phone socket triggers an action, it will receive the broadcast notification too. To prevent the phone from processing its own request twice, either mark the original socket for exclusion or have the phone await the server's confirmation response before updating locally.
CLUSTERED CONSIDERATIONS
If you have multiple Node.js servers, each server knows only its local sockets. If the phone connects to server A and the laptop to server B, sending to the laptop via server A fails. Use a Redis adapter to broadcast room messages across all servers. Socket.IO's adapter system handles this transparently.
Read the original → socket.io
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.