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.
NestJS provides the @nestjs/websockets package to work with WebSockets. The package comes with decorators and built-in support for WebSocket Gateways.
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.
A WebSocket gateway in NestJS acts as the main entry point for WebSocket connections and events. To create a WebSocket gateway, follow these steps:
Generate a new gateway using the NestJS CLI:
nest generate gateway chat
This will create a chat.gateway.ts file inside the src directory.
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);
}
}
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.
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.
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.