Skip to content

NestJS Web Push Notifications: Implementing Real-Time Notifications with Socket.IO and Redis

Interactive Diagram

새 탭 ↗

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.

Terminal window
npm i --save @nestjs/websockets @nestjs/platform-socket.io
  • Directorysrc/
    • Directoryevents/
      • events.gateway.ts
      • events.module.ts

Client side connecting to two NestJS gateways that receive injected values, services, providers and components Source: NestJS docs, Gateways, Kamil Mysliwiec and NestJS contributors, MIT

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)
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.

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:

  1. The frontend emits the 'patientJoin' event.
  2. The Gateway subscribes to the event.
  3. User information and the socketId are saved or updated in Redis.
  4. The complete active-user list is sent to the Admin user’s socketId.
  5. An individual notification is sent to each active user’s socketId.
DecoratorPurpose
@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
// Send to a specific socketId
this.server.to(socketId).emit('eventName', data);
// Send to all clients
this.server.emit('eventName', data);
// Send to a specific room
this.server.to('roomName').emit('eventName', data);
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 whose lastConnectedTime is within 60 seconds.
  • getAdminActive: Retrieves the session for the Admin user (the fixed username admin).
[
{
"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”
Terminal window
npm i --save @socket.io/admin-ui
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"
// }
});
}
}

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.

Clone the Socket.IO Admin UI source and host it yourself.

Terminal window
git clone https://github.com/socketio/socket.io-admin-ui.git
cd socket.io-admin-ui
npm install
npm run build
# Statically host the dist directory

Because it can be hosted using only static files, it can be deployed with Nginx or S3 + CloudFront.

  • 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
  • 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.
Terminal window
### 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: ndQXCVnn0ziFEoqCAAAN

The design for integrating this Web Push structure with Upstream/Downstream processes is covered in NestJS Upstream/Downstream Design.