I built the missing NestJS npm package: real-time user presence tracking with Socket.IO and Redis
If you've built a chat app, a support platform, or any collaborative tool with NestJS, you've
probably written some version of this code:
typescript // In your gateway... async handleConnection(client: Socket) { const userId = client.handshake.auth.userId; await this.redis.set(`presence:${userId}`, '1', 'EX', 30); this.server.emit('user:online', { userId }); }
async handleDisconnect(client: Socket) { const userId = client.handshake.auth.userId; await this.redis.del(`presence:${userId}`); this.server.emit('user:offline', { userId }); } And then you realize: what about users with multiple tabs open? What about ungraceful disconnects that never fire the disconnect event? What about querying who's online in a specific room? What about running this across 3 horizontally-scaled pods?
I've written this code β or a more complex version of it β on every real-time project I've worked on for the past 5 years.β¦