Chat App displays a live green dot next to every contact who is currently online. Presence state is maintained entirely through Socket.io connection and disconnection events — there is no polling, no heartbeat interval, and no additional database writes. The moment a user opens the app their presence is broadcast to every other connected client, and it disappears the instant they close their tab or lose connectivity.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/khushboodaryani/Chat-App/llms.txt
Use this file to discover all available pages before exploring further.
How Presence Tracking Works
Server-side: userSocketMap
The server keeps a plain JavaScript object that maps each online user’s_id to their current Socket.io socket ID:
| Trigger | Action |
|---|---|
Socket connection | Store userId → socketId in userSocketMap; broadcast all keys |
Socket disconnect | Delete userId from userSocketMap; broadcast all keys |
Client-side: SocketContext stores onlineUsers
TheSocketContextProvider listens for the getOnlineUsers event and stores the received array in local state:
onlineUsers is then exposed to the entire component tree through context:
Reading Presence in Components
Any component can check whether a specific user is online with a single line:Conversations component uses this pattern to conditionally render a green indicator badge next to each contact:
Presence Update Flow
User opens the app
SocketContextProvider detects a non-null authUser and opens a socket connection, passing userId in the query string.Server registers the connection
The server’s
connection handler stores userSocketMap[userId] = socket.id and calls io.emit("getOnlineUsers", Object.keys(userSocketMap)).All clients update their sidebar
Every connected
SocketContext receives the getOnlineUsers event and updates onlineUsers, causing the green dot to appear next to that user in every other user’s sidebar.User closes the tab or logs out
The socket closes. The server’s
disconnect handler fires, deletes the entry from userSocketMap, and broadcasts the updated list.Ephemeral Nature of Presence Data
Presence state lives only in memory.
userSocketMap is a plain JavaScript object in the server process — it is not written to MongoDB. If the server restarts (e.g. during a deploy or crash), the map is reset to an empty object. All clients must re-establish their socket connections before they reappear as online.For production deployments running multiple server instances, use the Socket.io Redis adapter so that userSocketMap is shared across all instances and presence data survives individual process restarts.API Summary
useSocketContext()
Returns
{ socket, onlineUsers } from SocketContext. Call this in any component that needs to check or react to presence.getOnlineUsers event
Emitted by the server to all clients whenever any user connects or disconnects. Payload is a
string[] of currently online user IDs.