惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
Google DeepMind News
Google DeepMind News
Stack Overflow Blog
Stack Overflow Blog
H
Help Net Security
MongoDB | Blog
MongoDB | Blog
I
InfoQ
N
Netflix TechBlog - Medium
T
Tailwind CSS Blog
量子位
博客园 - 叶小钗
月光博客
月光博客
IT之家
IT之家
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
S
SegmentFault 最新的问题
Engineering at Meta
Engineering at Meta
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
aimingoo的专栏
aimingoo的专栏
云风的 BLOG
云风的 BLOG
Vercel News
Vercel News
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
宝玉的分享
宝玉的分享

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
I built the missing NestJS npm package: real-time user pr...
Saifuddin Ti · 2026-05-08 · via DEV Community
Cover image for I built the missing NestJS npm package: real-time user presence tracking with Socket.IO and Redis

Saifuddin Tipu

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. Last week I searched npm for a dedicated NestJS
package that handled all of this. Nothing existed.

So I built it.

Introducing nestjs-socket-presence
A drop-in NestJS module that gives you complete, production-ready user presence tracking
via Socket.IO and Redis. Zero boilerplate. Works across multiple pods.


npm install nestjs-socket-presence ioredis
The problems it solves
Before I show the API, let me explain why naive presence tracking breaks in production.

Problem 1: The multiple tabs problem
A user opens your app in 3 browser tabs. Each tab opens a socket. They close tab 1.
Your naive implementation fires handleDisconnect and marks them offline — but they're
still connected via tabs 2 and 3.

nestjs-socket-presence tracks a set of socket IDs per user. The user only goes
offline when their last socket disconnects.

Problem 2: The ghost user problem
A user's laptop battery dies. No disconnect event fires. They're forever "online" in Redis.

nestjs-socket-presence uses Redis TTL expiry on every key. If the client doesn't send
a heartbeat within ttl seconds, they automatically go offline. No ghost users.

Problem 3: The multi-instance problem
You scale your NestJS app to 3 pods behind a load balancer. User A connects to Pod 1,
User B connects to Pod 3. Pod 1 has no idea User B exists.

nestjs-socket-presence stores all state in Redis — shared across every pod.
Presence is global, not local to a single process.

Problem 4: The room presence problem
You want to know: "which support agents are currently available in room support-tier-1?"
That's not just online/offline — it's presence scoped to a context.

nestjs-socket-presence has first-class room presence support.

Usage
1. Register the module

// app.module.ts
import { PresenceModule } from 'nestjs-socket-presence';

@Module({
  imports: [
    PresenceModule.register({
      redis: { host: 'localhost', port: 6379 },
      ttl: 30, // seconds — users go offline after 30s without heartbeat
    }),
  ],
})
export class AppModule {}
Works async too, for ConfigService:


PresenceModule.registerAsync({
  imports: [ConfigModule],
  useFactory: (config: ConfigService) => ({
    redis: { url: config.get('REDIS_URL') },
    ttl: 30,
  }),
  inject: [ConfigService],
})
2. Connect from the client

import { io } from 'socket.io-client';

const socket = io('http://localhost:3000', {
  auth: { userId: 'user-123' }, // userId in handshake → auto presence on connect
});
That's it. The user is tracked as online. On disconnect they go offline automatically.
The built-in PresenceGateway handles the entire lifecycle.

3. Keep presence alive (heartbeat)

// Client — call every ttl/2 seconds
setInterval(() => {
  socket.emit('presence:heartbeat', { userId: 'user-123' });
}, 15_000);
4. Query presence anywhere in your app

import { PresenceService } from 'nestjs-socket-presence';

@Injectable()
export class ChatService {
  constructor(private readonly presence: PresenceService) {}

  // Is a specific user online?
  async isAgentAvailable(agentId: string) {
    return this.presence.isOnline(agentId);
  }

  // Full presence details for a user
  async getUserStatus(userId: string) {
    return this.presence.getUserPresence(userId);
    // → { userId, online, socketIds, lastSeen, metadata? }
  }

  // Check hundreds of users at once — one Redis round-trip
  async getTeamStatus(userIds: string[]) {
    return this.presence.getBulkPresence(userIds);
    // → Map<string, boolean>
  }

  // Who's in a specific room right now?
  async getSupportRoomStatus(room: string) {
    return this.presence.getRoomPresence(room);
    // → { room, users: UserPresence[], onlineCount }
  }
}
5. Room presence (optional)

// Client joins a presence-tracked room
socket.emit('presence:room:join', { userId: 'user-123', room: 'support-tier-1' });

// Server pushes to the room when someone joins/leaves
socket.on('presence:room:join', ({ userId, room }) => {
  console.log(`${userId} joined ${room}`);
});

// Query who's currently in the room
const roomStatus = await this.presence.getRoomPresence('support-tier-1');
console.log(`${roomStatus.onlineCount} agents available`);
Real-world use cases
Customer support platforms — show which agents are available before routing a
customer's chat. If an agent closes their laptop, they go offline automatically after
the TTL expires.

Collaborative editors — "3 people are viewing this document right now." Track
presence per document room.

Live dashboards — know which operators are actively monitoring. Show a live
"who's watching" indicator.

Gaming lobbies — track which players are ready. Clean up presence automatically
when a player disconnects.

How the Redis keys are structured

presence:user:{userId}          HASH   → { userId, online, lastSeen, metadata? }
presence:user:{userId}:sockets  SET    → { socketId1, socketId2, ... }
presence:socket:{socketId}      STRING → userId
presence:room:{room}            SET    → { userId1, userId2, ... }
The socket→userId mapping is what enables clean multi-tab handling: on disconnect,
we look up which user owned that socket, remove it from their socket set, and only
mark them offline if the set is now empty.

Attach metadata to presence
Pass arbitrary metadata when a user comes online — useful for role, region, or
device type:


// Call from your own gateway or auth interceptor
await this.presenceService.setOnline(userId, socket.id, {
  role: 'senior-agent',
  region: 'us-east',
  department: 'billing',
});

// Read it back in room presence queries
const room = await this.presenceService.getRoomPresence('support-tier-1');
const billingAgents = room.users.filter(u => u.metadata?.department === 'billing');
What's next
This is v1.0.0. Things I'm planning for upcoming releases:

Presence events as NestJS events — emit via EventEmitter2 so you can hook into online/offline without touching the gateway
Presence guards — @RequireOnline() decorator for gateway message handlers
Analytics hook — optional callback on every presence change for logging/metrics
If any of these would solve a problem you have right now, open an issue or PR on GitHub —
I'd love to build it with the community.

Links
npm: https://www.npmjs.com/package/nestjs-socket-presence
GitHub: https://github.com/SaifuddinTipu/nestjs-socket-presence
22 unit tests. Full TypeScript with declaration files. MIT license.

If this saves you from copy-pasting presence code into your next NestJS project, drop
a ⭐ on GitHub — it helps others discover it.

Enter fullscreen mode Exit fullscreen mode