NestJS Web Push Notifications: Implementing Real-Time Notifications with Socket.IO and Redis
Real-time notifications (Web Push) are implemented on top of WebSocket, and user connection status is cached in Redis. Because NestJS natively supports Socket.IO through the Gateway pattern, it enables declarative management of the WebSocket lifecycle and events. This article covers implementing a Socket.IO Gateway, Redis-based user-session management, and configuring the Socket.IO Admin UI.
Installing Socket.IO
Section titled “Installing Socket.IO”npm i --save @nestjs/websockets @nestjs/platform-socket.ioWebSocket Gateway Structure
Section titled “WebSocket Gateway Structure”Directorysrc/
Directoryevents/
- events.gateway.ts
- events.module.ts

events.gateway.ts
Section titled “events.gateway.ts”import { SubscribeMessage, WebSocketGateway, OnGatewayInit, WebSocketServer, OnGatewayConnection, OnGatewayDisconnect, ConnectedSocket, MessageBody,} from '@nestjs/websockets';import { Socket, Server } from 'socket.io';import { Logger } from '@nestjs/common';import { instrument } from '@socket.io/admin-ui';
@WebSocketGateway({ cors: { origin: [ 'https://admin.socket.io', 'https://socketio-admin.example.com', 'http://localhost:8080', ], credentials: true, },})export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect{ @WebSocketServer() server: Server; private logger: Logger = new Logger('EventsGateway');
afterInit(server: Server) { this.logger.log(`WebSocket initialized: ${server.path()}`); instrument(server, { auth: false, // Disable Admin UI authentication (for testing) }); }
handleConnection(client: Socket, ...args: any[]) { this.logger.log(`Client connected: ${client.id}`); }
handleDisconnect(client: Socket) { this.logger.log(`Client disconnected: ${client.id}`); }}Key interfaces:
OnGatewayInit: Runs after the WebSocket server is initialized (afterInit)OnGatewayConnection: Runs when a client connects (handleConnection)OnGatewayDisconnect: Runs when a client disconnects (handleDisconnect)
Configuring CORS
Section titled “Configuring CORS”cors: { origin: [ 'https://admin.socket.io', // Public Admin UI 'https://socketio-admin.example.com', // Self-hosted Admin UI 'http://localhost:8080', // Development environment ], credentials: true,}To use the Socket.IO Admin UI, include the Admin UI URL in origin.
Event Subscribe & Emit
Section titled “Event Subscribe & Emit”User Registration Event
Section titled “User Registration Event”import { UserSessionCache } from './user-session.cache';
@WebSocketGateway({...})export class EventsGateway ... { constructor(private userSessionCache: UserSessionCache) {}
@SubscribeMessage('patientJoin') async joinRoom( @ConnectedSocket() client: Socket, @MessageBody() userName: string, ) { // 1. Save user information and socketId in Redis this.userSessionCache.addOrUpdate(userName, client.id);
// 2. Retrieve the list of active users const activeUsers = await this.userSessionCache.getAllActive(); const adminUser = await this.userSessionCache.getAdminActive();
// 3. Send the complete user list to the Admin user only this.server.to(adminUser.socketId).emit( 'patientList', activeUsers.map((x) => x.userName), );
// 4. Send a registration-complete notification to each user activeUsers.forEach((user) => { this.server.to(user.socketId).emit(user.userName + ':registered'); }); }}Workflow:
- The frontend emits the
'patientJoin'event. - The Gateway subscribes to the event.
- User information and the socketId are saved or updated in Redis.
- The complete active-user list is sent to the Admin user’s socketId.
- An individual notification is sent to each active user’s socketId.
Event Decorator Reference
Section titled “Event Decorator Reference”| Decorator | Purpose |
|---|---|
@SubscribeMessage('eventName') | Defines a handler that listens for a specific event |
@ConnectedSocket() | Injects Socket connection information (such as client.id) |
@MessageBody() | Injects the event payload (data) |
@WebSocketServer() | Injects the Socket.IO Server instance |
Socket Emit Methods
Section titled “Socket Emit Methods”// Send to a specific socketIdthis.server.to(socketId).emit('eventName', data);
// Send to all clientsthis.server.emit('eventName', data);
// Send to a specific roomthis.server.to('roomName').emit('eventName', data);Redis-Based User Session Management
Section titled “Redis-Based User Session Management”UserSessionCache Structure
Section titled “UserSessionCache Structure”import { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';import { Cache } from 'cache-manager';import * as moment from 'moment';
interface UserSession { userName: string; lastConnectedTime: string; socketId: string;}
@Injectable()export class UserSessionCache { constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
async addOrUpdate(userName: string, socketId: string): Promise<void> { const session: UserSession = { userName, lastConnectedTime: moment().format('YYYY-MM-DDTHH:mm:ss'), socketId, }; await this.cacheManager.set(`user:${userName}`, session, { ttl: 300 }); // 5-minute TTL }
async getAllActive(): Promise<UserSession[]> { const keys = await this.cacheManager.store.keys('user:*'); const sessions: UserSession[] = [];
for (const key of keys) { const session = await this.cacheManager.get<UserSession>(key); if (session && this.isActive(session)) { sessions.push(session); } }
return sessions; }
async getAdminActive(): Promise<UserSession> { return await this.cacheManager.get<UserSession>('user:admin'); }
private isActive(session: UserSession): boolean { const lastConnected = moment(session.lastConnectedTime); const now = moment(); return now.diff(lastConnected, 'seconds') < 60; // Active within 60 seconds }}Key logic:
- addOrUpdate: Stores the user name and socketId in Redis and updates
lastConnectedTime. - getAllActive: Retrieves all
user:*keys in Redis and returns only users whoselastConnectedTimeis within 60 seconds. - getAdminActive: Retrieves the session for the Admin user (the fixed username
admin).
Redis Data Example
Section titled “Redis Data Example”[ { "userName": "admin", "lastConnectedTime": "2022-08-03T06:53:20", "socketId": "8dvBgASLXbMkv2i4AAAL" }, { "userName": "Christian Dior", "lastConnectedTime": "2022-08-03T06:52:20", "socketId": "enOuMMdNJtna6WnZAAAH" }, { "userName": "Coco Chanel", "lastConnectedTime": "2022-08-03T07:00:04", "socketId": "ndQXCVnn0ziFEoqCAAAN" }]Socket.IO Admin UI: Monitoring Connection Status
Section titled “Socket.IO Admin UI: Monitoring Connection Status”Installation
Section titled “Installation”npm i --save @socket.io/admin-uiEnabling the Admin UI in the Gateway
Section titled “Enabling the Admin UI in the Gateway”import { instrument } from '@socket.io/admin-ui';
@WebSocketGateway({ cors: { origin: [ 'https://admin.socket.io', 'https://socketio-admin.example.com', ], credentials: true, },})export class EventsGateway implements OnGatewayInit, ... { afterInit(server: Server) { this.logger.log(`WebSocket initialized: ${server.path()}`);
instrument(server, { auth: false, // Disable authentication (for development) // auth: { // type: "basic", // username: "admin", // password: "admin123" // } }); }}How to Use the Admin UI
Section titled “How to Use the Admin UI”1. Public Admin UI (https://admin.socket.io)
Section titled “1. Public Admin UI (https://admin.socket.io)”Enter the server URL in the official Socket.IO Admin UI to begin monitoring immediately.
Security note:
- Because anyone can access the Public Admin UI, use it only in a development environment.
- In production, always use an auth configuration or a self-hosted Admin UI.
2. Self-hosted Admin UI
Section titled “2. Self-hosted Admin UI”Clone the Socket.IO Admin UI source and host it yourself.
git clone https://github.com/socketio/socket.io-admin-ui.gitcd socket.io-admin-uinpm installnpm run build# Statically host the dist directoryBecause it can be hosted using only static files, it can be deployed with Nginx or S3 + CloudFront.
Admin UI Features
Section titled “Admin UI Features”- Socket connection-status monitoring: Number of currently connected clients and the socketId list
- Event-send testing: Emit a specific event directly from the Admin UI
- Server-status monitoring: Memory usage, uptime, and transport method
- Namespace lookup: Client lists for each namespace, such as
/and/admin
Practical Implementation Principles
Section titled “Practical Implementation Principles”- Store socketId in Redis: A socketId is required to send messages to individual users.
- Determine activity using lastConnectedTime: Redis TTL alone is insufficient; the last activity time must also be considered.
- Use a fixed username for the Admin user: Distinguishes the user authorized to receive the complete user list.
- Configure authentication for the Admin UI: Leaving it open without authentication in production directly leads to security incidents.
- Configure CORS explicitly: Without the Admin UI origin, the Admin UI cannot connect.
Connection Log Example
Section titled “Connection Log Example”### WebSocket server initialization[Winston] Info 2022-08-03T06:24:19+00:00 WebSocket initialized: /socket.io
### Client connection/disconnection[Winston] Info 2022-08-03T06:32:51+00:00 Client connected: 8dvBgASLXbMkv2i4AAAL[Winston] Info 2022-08-03T06:58:15+00:00 Client disconnected: enOuMMdNJtna6WnZAAAH[Winston] Info 2022-08-03T06:58:15+00:00 Client connected: ndQXCVnn0ziFEoqCAAANNext Steps
Section titled “Next Steps”The design for integrating this Web Push structure with Upstream/Downstream processes is covered in NestJS Upstream/Downstream Design.