Presence Tracking
The PresenceManager helps you track which users are currently online and their status. It’s useful for showing active users, user lists, or online indicators.Installation
Presence tracking is included in the main socket-serve package:Basic Usage
Track User Status
Get Online Users
User Metadata
Store additional information about users:Presence in Rooms
Track presence per room:Heartbeat & Timeouts
Automatically detect when users disconnect:API Reference
PresenceManager
Constructor
heartbeatInterval?: number- How often to check for heartbeats (default: 30000)timeout?: number- When to consider user offline (default: 60000)
Methods
setStatus(userId: string, metadata: object)
Set user’s online status and metadata.
getOnlineUsers(): Promise<string[]>
Get list of all online user IDs.
getUserInfo(userId: string): Promise<object | null>
Get user’s presence information.
isOnline(userId: string): Promise<boolean>
Check if user is currently online.
getUsersInRoom(roomId: string): Promise<string[]>
Get all users in a specific room.
joinRoom(userId: string, roomId: string): Promise<void>
Mark user as present in a room.
leaveRoom(userId: string, roomId: string): Promise<void>
Remove user from room presence.
heartbeat(userId: string): Promise<void>
Update user’s last activity timestamp.
Events
onJoin(callback: (userId: string, metadata: object) => void)
Called when a user comes online.
onLeave(callback: (userId: string) => void)
Called when a user goes offline.
onTimeout(callback: (userId: string) => void)
Called when a user times out due to inactivity.
Example: Online Users List
Best Practices
- Always clean up presence data on disconnect
- Use heartbeats for accurate presence tracking
- Store minimal metadata to reduce Redis memory
- Implement timeout handling for abandoned connections
- Consider using rooms for large-scale presence tracking
- Cache online user lists for frequently accessed data