NodeJS

    Using WebSockets in NestJS for Real-Time Communication

     


    Introduction

    Modern business applications need real-time communication systems to deliver interactive capabilities through chat software and live system alerts as well as team collaboration functions. WebSockets allow a single TCP connection to support two-way data transmission thus making them fitting for live updates. Developers can easily implement WebSockets through the modern Node.js framework NestJS which provides this solution.

    Setting Up WebSockets in NestJS

    NestJS provides the @nestjs/websockets package to work with WebSockets. The package comes with decorators and built-in support for WebSocket Gateways.

    Installation

    First install the necessary package:

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

     

    Note: The default WebSocket implementation in NestJS is based on Socket.IO, but you can also use other WebSocket libraries like ws if needed.

    Creating a WebSocket Gateway

    A WebSocket gateway in NestJS acts as the main entry point for WebSocket connections and events. To create a WebSocket gateway, follow these steps:

    Step 1: Create a Gateway

    Generate a new gateway using the NestJS CLI:

    nest generate gateway chat

    This will create a chat.gateway.ts file inside the src directory.

    Step 2: Implement the Gateway

    Modify the chat.gateway.ts file as follows:

    import { WebSocketGateway, SubscribeMessage, MessageBody, OnGatewayConnection,OnGatewayDisconnect, WebSocketServer } from '@nestjs/websockets';import { Server, Socket } from 'socket.io';@WebSocketGateway({ cors: true })export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {@WebSocketServer()server: Server;private users: number = 0;handleConnection(client: Socket) {this.users++;this.server.emit('usersCount', this.users);console.log(`Client connected: ${client.id}`);}handleDisconnect(client: Socket) {this.users--;this.server.emit('usersCount', this.users);console.log(`Client disconnected: ${client.id}`);}@SubscribeMessage('sendMessage')handleMessage(@MessageBody() message: { sender: string; content: string }) {this.server.emit('receiveMessage', message);}}

    Explanation

    • @WebSocketGateway(): Declares a WebSocket gateway.
    • @WebSocketServer(): Injects the WebSocket server instance.
    • handleConnection(): Listens for new client connections and emits the updated user count.
    • handleDisconnect(): Detects when a client disconnects and updates the user count.
    • @SubscribeMessage('sendMessage'): Listens for an event (sendMessage) and broadcasts the received message to all connected clients.

    Integrating WebSockets in a NestJS Application

    To use the ChatGateway, register it in a module. Open app.module.ts and add:

    import { Module } from '@nestjs/common';import { ChatGateway } from './chat.gateway';@Module({providers: [ChatGateway],})export class AppModule {}

    With this, WebSockets are fully functional within your NestJS app.

    Testing WebSockets

    To test the WebSocket connection, you can use a simple frontend with Socket.IO client:

    Example HTML + JavaScript Client

    Create an index.html file:

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>WebSocket Chat</title><script src="https://cdn.socket.io/4.0.1/socket.io.min.js"></script></head><body><input id="message" type="text" placeholder="Type a message..."><button onclick="sendMessage()">Send</button><ul id="messages"></ul><script>const socket = io('http://localhost:3000');socket.on('receiveMessage', (msg) => {const li = document.createElement('li');li.innerText = `${msg.sender}: ${msg.content}`;document.getElementById('messages').appendChild(li);});function sendMessage() {const message = document.getElementById('message').value;socket.emit('sendMessage', { sender: 'User', content: message });document.getElementById('message').value = '';}</script></body></html>

     

    Launch the NestJS server with npm run start while viewing index.html in a browser where you will experience real-time messaging functionality.

    Conclusion

    The real-time communication capabilities of WebSockets can easily be implemented through decorators and built-in support in NestJS.

    Ready to transform your business with our technology solutions?  Contact us today to Leverage Our Nodejs Expertise.

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    NodeJS

    Related Center Of Excellence