Building a Real-Time Dashboard with NestJS and WebSockets

@rnab
3 min readJan 28, 2025

--

In today’s fast-paced world, real-time applications have become a standard for delivering instantaneous information to users. From notifications to live feeds, users expect instant updates. One of the most efficient ways to implement real-time communication in web applications is through WebSockets. In this article, we will explore how to build a real-time dashboard using NestJS, a modern Node.js framework, and WebSockets.

Why NestJS and WebSockets?

NestJS is a powerful framework for building server-side applications. It is built with TypeScript and takes advantage of the modular architecture provided by Angular, which makes it ideal for creating scalable and maintainable server-side applications. WebSockets, on the other hand, provide full-duplex communication channels over a single TCP connection, allowing servers and clients to send messages to each other independently and instantly.

Combining the architectural strength of NestJS with the real-time communication capabilities of WebSockets, we can build efficient and robust real-time dashboards.

Getting Started

First, ensure you have Node.js and npm installed. Let’s start by setting up a new NestJS project.

npm i -g @nestjs/cli
nest new real-time-dashboard

Navigate into your project directory:

cd real-time-dashboard

Setting Up WebSockets with NestJS

NestJS has a built-in package for handling WebSocket communications called @nestjs/websockets, which provides the basic necessities to work with WebSockets out of the box.

Installing WebSocket Package

Although included by default with NestJS, ensure you have the package installed:

npm install @nestjs/websockets @nestjs/platform-socket.io

Creating a WebSocket Gateway

A WebSocket gateway in NestJS is a class that handles WebSocket communications, similar to a controller in REST APIs.

Let’s create a WebSocket gateway for our real-time dashboard:

import { SubscribeMessage, WebSocketGateway, WebSocketServer, OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway()
export class DashboardGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer() server: Server;

afterInit(server: Server) {
console.log('WebSocket server initialized');
}

handleConnection(client: Socket, ...args: any[]) {
console.log(`Client connected: ${client.id}`);
}

handleDisconnect(client: Socket) {
console.log(`Client disconnected: ${client.id}`);
}

@SubscribeMessage('sendMessage')
handleMessage(client: Socket, payload: string): void {
console.log(`Message received: ${payload}`);
this.server.emit('receiveMessage', payload);
}
}

Registering the Gateway

Now, we need to register our gateway in a module. For this, we’ll leverage NestJS’s dependency injection system.

import { Module } from '@nestjs/common';
import { DashboardGateway } from './dashboard.gateway';

@Module({
providers: [DashboardGateway],
})
export class DashboardModule {}

Finally, import this module into the application’s main module (app.module.ts).

import { Module } from '@nestjs/common';
import { DashboardModule } from './dashboard/dashboard.module';

@Module({
imports: [DashboardModule],
})
export class AppModule {}

Integrating with a Frontend

To test our WebSocket server, having a simple frontend client can help. We’ll use plain HTML and JavaScript with Socket.IO client.

Create a file index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real-Time Dashboard</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<h1>Real-Time Dashboard</h1>
<input type="text" id="messageInput" placeholder="Type a message...">
<button id="sendButton">Send</button>
<ul id="messages"></ul>

<script>
const socket = io('http://localhost:3000');
const messageInput = document.getElementById('messageInput');
const sendButton = document.getElementById('sendButton');
const messages = document.getElementById('messages');

sendButton.addEventListener('click', () => {
const message = messageInput.value;
socket.emit('sendMessage', message);
messageInput.value = '';
});

socket.on('receiveMessage', (message) => {
const li = document.createElement('li');
li.textContent = message;
messages.appendChild(li);
});
</script>
</body>
</html>

Running the Application

To start the application, ensure your NestJS application is running. Then, open index.html in a browser. You can run the NestJS server:

npm run start

Open index.html in the browser and play around with sending messages. You should see messages appearing in the list dynamically.

Conclusion

In this article, we demonstrated how to build a real-time dashboard using NestJS and WebSockets. We set up a basic WebSocket server using the NestJS framework and integrated it with a simple frontend to visualize real-time messaging. This powerful combination can be further extended to support more complex real-time features like live notifications, data streaming, and collaborative applications. NestJS and WebSockets provide the perfect platform for building modern, responsive, and dynamic dashboards. Happy coding!

--

--

@rnab
@rnab

Written by @rnab

Typescript, Devops, Kubernetes, AWS, AI/ML, Algo Trading

No responses yet