Scroll Top

Easiest Way to Implement WebSockets in NestJS

nestjs websocket

WebSockets are a powerful tool for enabling real-time communication between the client and server, and in this post, we’ll walk you through how to implement WebSockets in NestJS. With NestJS being a popular and efficient framework for building scalable and maintainable server-side applications, using WebSockets in this environment will allow you to build highly interactive and responsive applications.

In this blog post, we will explain the process of integrating WebSockets in NestJS, covering installation, configuration, and real-world usage. If you’re looking to leverage NestJS for your next real-time application, this guide will give you a comprehensive understanding of how to get started.

For businesses looking to build cutting-edge, scalable applications, hiring experienced NestJS developers is essential. Hire NestJS Developers from Zignuts and build robust, real-time communication features for your platform with ease.

What Is NestJS WebSocket?

Before diving into the implementation of WebSockets in NestJS, let’s understand what WebSockets are and why they are so useful in modern web applications.

WebSockets Explained

WebSockets provide a full-duplex communication channel over a single, long-lived TCP connection, allowing bidirectional communication between client and server. This is especially useful for applications that require real-time data such as chat applications, live notifications, or gaming platforms.

Real-Time Applications with WebSockets

In a traditional HTTP request-response model, the client sends a request, and the server responds. However, with WebSockets, communication happens in both directions, making it an ideal choice for real-time applications that require frequent updates or instantaneous data exchange.

Setting Up WebSockets in NestJS

Now that we know the basics, let’s dive into how you can set up WebSockets in your NestJS project.

Install Required Packages

First, you need to install the necessary dependencies to use WebSockets in NestJS. If you don’t already have a NestJS project, you can create one using the following command:

nest new websocket-demo

After setting up your project, you can install Socket.IO (or any other WebSocket library of your choice) with:

npm install @nestjs/websockets socket.io

Configuring NestJS WebSocket

Once the dependencies are installed, you need to configure NestJS to support WebSockets. NestJS provides an integrated WebSocket module that allows you to create WebSocket gateways with minimal configuration.
To create a WebSocket gateway, you can use the following steps:

Create a Gateway

NestJS provides a Gateway decorator to define a WebSocket gateway in your application. Create a new file called chat.gateway.ts:

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

@WebSocketGateway(3001) // The port on which the WebSocket server will run
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer() server: Server;

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

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

  // Custom method to broadcast a message to all connected clients
  sendMessage(message: string) {
    this.server.emit('message', message);
  }
}

Register the Gateway

After creating the WebSocket gateway, don’t forget to register it inside the module. Add the ChatGateway to your module’s providers:

import { Module } from '@nestjs/common';
import { ChatGateway } from './chat.gateway';

@Module({
  providers: [ChatGateway],
})
export class ChatModule {}

This setup will allow your NestJS app to start listening for WebSocket connections on port 3001.

Working with WebSocket Events

WebSockets use events to handle communication between the server and the client. In the example above, we emitted a message event. But let’s dive deeper into handling different types of events.

Emitting and Listening to Events

With NestJS, you can emit events and listen for them easily using decorators. Here is an example of how to handle multiple types of events.

@WebSocketGateway()
export class ChatGateway {
  @WebSocketServer() server: Server;

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

  @SubscribeMessage('join')
  handleJoinRoom(client: Socket, room: string): void {
    client.join(room);
    this.server.to(room).emit('message', `${client.id} has joined the room`);
  }
}

In this code snippet, the server listens for message and join events from clients. When a message event is received, it will broadcast the message to all connected clients. If the join event is triggered, the client will be added to a specific room.

Handling Client-Side WebSocket

On the client side, you can easily communicate with the server using Socket.IO. Here’s an example of how to emit and listen for events in a client-side JavaScript application:

const socket = io('http://localhost:3001');

// Sending a message
socket.emit('message', 'Hello, server!');

// Receiving a message
socket.on('message', (message) => {
  console.log('Received message:', message);
});

Testing WebSocket Events with Postman Desktop

Let us now see how to test a websocket event using Postman

1. Open Postman.

2. In the top left corner, click the “New” button. A drop-down menu will appear.

Nestjs websocket

3. Select “WebSocket”.

4. In the request URL field in the new tab, enter the URL of your WebSocket server. “ws://” is for unsecured connections or “wss://” is for secured connections.

Nestjs websocket

5. In the “Headers” tab, add the headers required to make the connection and click “Connect”.

6. To send a message, select the type (Text, JSON, Binary) and add the data in the “Message” tab as shown below (example for JSON data). You can also send the event “JOIN” and click on “Send”.

Nestjs websocket

7. To listen to an event, go to the Events tab, add the event name and toggle it to start listening to that event.

Nestjs websocket

Best Practices for NestJS WebSocket Implementation

Handle Errors Gracefully

WebSocket connections can sometimes experience errors due to network issues. Always handle these errors by subscribing to the error event:

client.on('error', (error) => {
  console.error('Error in WebSocket connection:', error);
});

Use Rooms for Group Messaging

When you want to send messages to specific groups of users, Socket.IO rooms are a great way to achieve this. By using rooms, you can create more organized and scalable WebSocket communication.

Scale with Redis or NATS (H3)

If your application grows and you need to scale horizontally (across multiple servers), consider using Redis or NATS to manage WebSocket events across different instances of your application.

Hire Professional NestJS Developers

Integrating WebSockets in NestJS requires a deep understanding of real-time communication, and setting up a robust system can be complex. If you want to build a seamless real-time feature with NestJS, consider partnering with a skilled team of developers. Hire NestJS Developers at Zignuts to ensure that your WebSocket implementation is optimised for performance, scalability, and reliability.

Conclusion:

In this blog post, we’ve explored how to implement WebSockets in NestJS. From understanding the basics of WebSockets to configuring and handling events in NestJS, you now have the foundation to start building real-time applications. With the ease of integrating WebSocket support and scalability in NestJS, you can create robust real-time features for your next project.

If you’re looking for a top-rated NestJS development company, don’t hesitate to contact Zignuts and take your real-time applications to the next level. Hire NestJS Developers today and build the future of communication in your application.

close-link
Register to ThemeSelection 🚀

Prefer to Login/Register with:

OR
Already Have Account?

By Signin or Signup to ThemeSelection.com using social accounts or login/register form, You are agreeing to our Terms & Conditions and Privacy Policy
close-link
Reset Your Password 🔐

Enter your username/email address, we will send you reset password link on it. 🔓

Privacy Preferences
When you visit our website, it may store information through your browser from specific services, usually in form of cookies. Here you can change your privacy preferences. Please note that blocking some types of cookies may impact your experience on our website and the services we offer.