In the world of modern web applications, real-time communication is a key feature that enhances user experience and improves interactivity. WebSockets provide a way to achieve this by establishing a persistent connection between the client and the server. In this blog post, we will explore how to integrate WebSocket functionality into your NestJS application, enabling real-time updates and interaction.
What are WebSockets?
WebSockets are a communication protocol that allows for full-duplex communication channels over a single TCP connection. Unlike traditional HTTP requests where the client must initiate the communication, WebSockets enable servers to push updates to clients, which is particularly useful for applications like chat systems, live notifications, collaborative tools, and more.
Setting Up a NestJS Application
Before diving into WebSocket integration, let's make sure you have a basic NestJS application set up. If you haven’t done this yet, you can create a new NestJS project using the Nest CLI:
npm i -g @nestjs/cli nest new my-websocket-app cd my-websocket-app
Installing Required Packages
NestJS provides a built-in package for WebSocket integration, but for added functionality, we can use socket.io
. To install it, run:
npm install @nestjs/websockets socket.io
Creating a WebSocket Gateway
A gateway in NestJS acts as a WebSocket server. It listens for incoming connections and handles messages. Let's create a simple WebSocket gateway:
-
Generate the Gateway
You can use the Nest CLI to generate a new gateway:
nest generate gateway chat
This will create a
chat.gateway.ts
file in your project. -
Implementing the Gateway
Inside
chat.gateway.ts
, you can implement the WebSocket event listeners and emitters. Here’s an example:import { WebSocketGateway, WebSocketServer, SubscribeMessage, MessageBody, OnGatewayInit, Socket, } from '@nestjs/websockets'; import { Server } from 'socket.io'; @WebSocketGateway() export class ChatGateway implements OnGatewayInit { @WebSocketServer() server: Server; afterInit(server: Server) { console.log('WebSocket Initialized'); } @SubscribeMessage('message') handleMessage(client: Socket, payload: { sender: string; message: string }) { console.log(`Received message: ${payload.message} from ${payload.sender}`); this.server.emit('message', payload); } }
In this code:
- The
@WebSocketGateway()
decorator marks the class as a WebSocket gateway. - The
afterInit
method logs a message when the WebSocket server is initialized. - The
handleMessage
method listens for incomingmessage
events from clients, logs the data, and then emits the message to all connected clients.
- The
Connecting from the Client
To test our WebSocket gateway, we need a client that can connect to it. You can use vanilla JavaScript or a framework of your choice. Here’s a simple HTML file that demonstrates how to connect to the WebSocket server and send messages:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebSocket Client</title> <script src="/socket.io/socket.io.js"></script> </head> <body> <input id="sender" type="text" placeholder="Your name" /> <input id="message" type="text" placeholder="Enter message" /> <button id="sendBtn">Send Message</button> <div id="messages"></div> <script> const socket = io('http://localhost:3000'); // Adjust the port if needed socket.on('message', ({ sender, message }) => { const messagesDiv = document.getElementById('messages'); messagesDiv.innerHTML += ``; }); document.getElementById('sendBtn').onclick = function () { const sender = document.getElementById('sender').value; const message = document.getElementById('message').value; socket.emit('message', { sender, message }); document.getElementById('message').value = ''; // Clear input }; </script> </body> </html>
Running the Application
-
Start the NestJS application:
npm run start
-
Open your browser and navigate to the HTML file you created. You can open multiple tabs to simulate different clients.
-
Enter a name and a message in the input fields, click the send button, and watch as messages appear in real-time across all connected clients.
Conclusion
Integrating WebSockets in your NestJS application allows for real-time communication, enhancing user interaction significantly. With the simple setup demonstrated above, you can build chat applications, live notifications, or collaborative platforms easily. The power of WebSockets in conjunction with the structured framework of NestJS opens up exciting possibilities for modern web development.
Keep experimenting with different events and message types to suit your application's needs. Happy coding!