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:
Step 1: Set Up a NestJS Project
If you don’t already have a NestJS project, create one with:
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:
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:
- Open
chat.gateway.ts
and replace its contents with the following code:
Here’s a quick breakdown:
@WebSocketServer()
provides access to the Socket.IO server instance.afterInit()
,handleConnection()
, andhandleDisconnect()
manage connection events.@SubscribeMessage('message')
listens for incomingmessage
events and rebroadcasts them.
Step 4: Configure the WebSocket Gateway
Customize the WebSocket settings by modifying @WebSocketGateway
as follows:
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:
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:
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:
- 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.