Implementing Socket.IO in NestJS for Real-Time Communication

Implementing Socket.IO in NestJS for Real-Time Communication

Adding real-time functionality is essential for dynamic applications, such as messaging platforms, live notifications, and online games. This guide will walk you through integrating Socket.IO into a NestJS backend, enabling you to build a server that communicates in real-time with connected clients.

Prerequisites

To get started, make sure you have:

  • Node.js installed
  • Basic familiarity with NestJS
  • A NestJS project ready to go

Step 1: Set Up a NestJS Project

If you don’t already have a NestJS project, create one with:

bash

npx @nestjs/cli new nestjs-socketio-demo cd nestjs-socketio-demo


Navigate into the directory to find the application’s basic structure. We’ll expand on this to add WebSocket functionality.

Step 2: Install Socket.IO

Since Socket.IO doesn’t come with NestJS, let’s install it with:

bash

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


This command adds @nestjs/platform-socket.io for creating WebSocket gateways in NestJS, along with the socket.io library.

Step 3: Create a WebSocket Gateway

NestJS offers a @WebSocketGateway decorator that sets up gateways for WebSocket communication, defining listeners and emitters.

  • Generate a new gateway file:

bash
npx nest generate gateway chat

  • Open chat.gateway.ts and replace its contents with the following code:

typescript

import { WebSocketGateway, SubscribeMessage, MessageBody, WebSocketServer, OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway() export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect { @WebSocketServer() server: Server; afterInit(server: Server) { console.log('WebSocket server initialized'); } handleConnection(client: Socket) { console.log(`Client connected: ${client.id}`); } handleDisconnect(client: Socket) { console.log(`Client disconnected: ${client.id}`); } @SubscribeMessage('message') handleMessage(@MessageBody() message: { sender: string; text: string }): void { this.server.emit('message', message); } }


Here’s a quick breakdown:

  • @WebSocketServer() provides access to the Socket.IO server instance.
  • afterInit(), handleConnection(), and handleDisconnect() manage connection events.
  • @SubscribeMessage('message') listens for incoming message events and rebroadcasts them.

Step 4: Configure the WebSocket Gateway

Customize the WebSocket settings by modifying @WebSocketGateway as follows:

typescript

@WebSocketGateway({ cors: { origin: '*', // Allows requests from any origin }, namespace: '/chat' // Defines a specific namespace for this gateway })


This setup allows cross-origin requests and creates a /chat namespace for this gateway.

Step 5: Add the Gateway to a Module

To activate the gateway, add ChatGateway to your main module. Open app.module.ts and place ChatGateway in the providers array:

typescript

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


Step 6: Set Up a Basic Client for Testing

To test your WebSocket server, create a simple client-side interface. This index.html file will connect to the server and display messages from connected clients.

Create an index.html file and add this code:

html

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


This HTML provides a simple chat interface where each client can enter messages, and those messages are sent to the server, which then broadcasts them to all connected clients.

Step 7: Run and Test the Application

  • Start your NestJS server:

bash

npm run start

  • Open the index.html file in multiple browser tabs to simulate multiple clients. When you send a message, it will appear across all open tabs, demonstrating real-time broadcasting.

Conclusion

In this tutorial, you learned how to integrate Socket.IO into a NestJS backend, enabling real-time communication between clients and the server. You can expand on this by implementing additional features like chat rooms, private messaging, or even adding authentication.

This setup serves as a solid foundation for any application requiring instant updates, such as collaborative tools or live notification systems.

Post a Comment

Previous Post Next Post