From REST to Real-Time: WebSockets with NestJS

From REST to Real-Time: WebSockets with NestJS

·

4 min read

In today’s fast-paced digital world, real-time communication is a game-changer. Whether it’s chat applications, live notifications, collaborative tools, or stock market dashboards, users expect instant updates without constantly refreshing their screens. WebSockets provide a powerful way to achieve this by enabling two-way communication between clients and servers.

NestJS, a progressive Node.js framework, simplifies WebSocket integration with its modular architecture and built-in support for WebSocket gateways. In this blog, we’ll explore how to use WebSockets in NestJS to build real-time applications efficiently.

How WebSockets Work and Why They Are Useful?

Traditional web applications rely on HTTP, where the client sends a request and waits for the server to respond. This request-response model is inefficient for real-time updates, as it requires constant polling or long polling, both of which introduce latency and unnecessary network overhead.

WebSockets solve this problem by establishing a persistent, bi-directional communication channel between the client and server. Once a WebSocket connection is established, both parties can send and receive messages instantly without repeated requests. This makes WebSockets ideal for applications like:

  • Chat applications (WhatsApp, Slack)

  • Live notifications (real-time alerts, updates)

  • Collaborative tools (Google Docs, Figma)

  • Stock market dashboards (real-time price updates)

Setting Up WebSockets in a NestJS Application

For real-time communication in NestJS, we will be using Socket.IO, a library that simplifies WebSocket-based communication by adding features like event-driven messaging, automatic reconnections, and fallback support for older browsers.

NestJS provides first-class support for Socket.IO through the @nestjs/websockets and @nestjs/platform-socket.io packages, making it easy to integrate real-time features into our applications.Step 1: Install the required dependencies

Step 1: Installing Dependencies

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

Step 2: Implementing a WebSocket Gateway in NestJS

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

@WebSocketGateway()
export class MySocketGateway implements OnGatewayConnection, OnGatewayDisconnect {

  @WebSocketServer()
  server: Server;

  handleConnection(client: Socket) {
    console.log('Client connected:', client.id);
  }

  handleDisconnect(client: Socket) {
    console.log('Client disconnected:', client.id);
  }

  @SubscribeMessage('message')
  handleMessage(client: Socket, @MessageBody() data: string): void {
    console.log('Received message:', data);
  }
}

@WebSocketGateway({ path: '/ws' }) → Starts a WebSocket server at ws://localhost:3000/ws.

@WebSocketServer() → Injects the WebSocket server instance.

• handleConnection() and handleDisconnect() → Manage client connections.

@SubscribeMessage('message') → Handles incoming messages and responds to the client.

Step 3: Handling Events and Messages Between the Client and Server

For broadcasting messages to all connected clients:

handleMessage(client: Socket, @MessageBody() data: string): void {
  this.server.emit('response', `Broadcast: ${data}`); // Sends to all clients
}

To send message only to the connected client:

handleMessage(client: Socket, @MessageBody() data: string): void {
  client.emit('response', `Broadcast: ${data}`); // Sends to all clients
}

Step 4: Configuring WebSockets in main.ts and AppModule

Before testing WebSockets, we need to ensure that our NestJS application is correctly configured to support Socket.IO WebSockets.

Set Up WebSockets in main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { IoAdapter } from '@nestjs/platform-socket.io';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // Set the WebSocket adapter
  app.useWebSocketAdapter(new IoAdapter(app));

  await app.listen(3000);
  console.log('Server running on http://localhost:3000');
}
bootstrap();

Import WebSocketModule in AppModule

Modify your app.module.ts file to ensure WebSockets are properly registered:

import { Module } from '@nestjs/common';
import { MySocketGateway } from './my-socket.gateway';

@Module({
  providers: [MySocketGateway], // Register the WebSocket gateway
})
export class AppModule {}

Testing WebSockets in NestJS Using Postman

Now that the WebSocket server is up and running, it’s time to put ‘em to test.

While WebSockets are typically tested using frontend clients or command-line tools like wscat, Postman also provides a way to test Socket.IO WebSockets.

Step 1: Open Postman and Set Up a WebSocket Connection

  1. Select New > Socket.IO to open a Socket.IO request in a new tab. (In the Postman desktop app, you can also select ⌘+N or Ctrl+N.)

  2. Enter a WebSocket server URL. A WebSocket URL begins with ws:// or wss://.

  3. Select Connect.

To disconnect your WebSocket request's connection, select Disconnect.

You can additionally listen to specific events:

After connecting, you can send messages on to a specific event, by default the event is message.

That’s it for now! With this setup, you’re now ready to build real-time applications in NestJS, such as chat apps, live notifications, and collaborative tools. 🚀

In our next blog, we’ll dive into Managing Connections and Scaling WebSocket Applications. Stay tuned! 😊

References: