How to Build Real-Time Applications Using NestJS and WebSockets
In today’s digital landscape, real-time applications are becoming increasingly essential. From chat applications to live notifications, they enhance user engagement and provide instant feedback. If you're a developer looking to harness the power of real-time communication, leveraging NestJS with WebSockets is an excellent choice. In this article, we’ll guide you through the process of building a real-time application using these technologies.
What is NestJS?
NestJS is a progressive Node.js framework designed for building efficient, reliable, and scalable server-side applications. It is built with TypeScript and incorporates elements from both OOP (Object-Oriented Programming) and Functional Programming. NestJS is particularly well-suited for building microservices and server-side applications, making it a great choice for real-time applications.
Understanding WebSockets
WebSockets is a communication protocol that provides full-duplex communication channels over a single TCP connection. Unlike traditional HTTP requests, WebSockets allow for persistent connections, enabling servers to send messages to clients in real time. This makes WebSockets ideal for applications that require instant updates, such as gaming, messaging, or live data feeds.
Use Cases for Real-Time Applications
Before diving into the coding aspect, let's explore some common use cases for real-time applications:
- Chat Applications: Instant messaging platforms that require real-time message delivery.
- Collaborative Tools: Applications like Google Docs that allow multiple users to edit documents simultaneously.
- Live Notifications: Systems that push alerts and updates to users, such as stock trading platforms or social media.
- Online Gaming: Multiplayer games that require real-time interaction between players.
Setting Up Your NestJS Project
Step 1: Install NestJS CLI
To get started, you need to have Node.js installed. Once you have that, install the NestJS CLI globally:
npm install -g @nestjs/cli
Step 2: Create a New Project
Create a new NestJS project by running:
nest new real-time-app
Navigate into your project directory:
cd real-time-app
Step 3: Install WebSocket Dependencies
NestJS supports WebSockets out of the box, but you need to install the required packages:
npm install --save @nestjs/websockets socket.io
Building a Simple Real-Time Chat Application
Let’s create a simple real-time chat application using NestJS and WebSockets.
Step 4: Create a Gateway
A gateway is a class that handles WebSocket connections. Create a new file named chat.gateway.ts
in the src
directory:
import {
WebSocketGateway,
WebSocketServer,
OnGatewayConnection,
OnGatewayDisconnect,
SubscribeMessage,
WebSocketAdapter,
} from '@nestjs/websockets';
import { Server } from 'socket.io';
@WebSocketGateway()
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
server: Server;
handleConnection(client: any) {
console.log(`Client connected: ${client.id}`);
}
handleDisconnect(client: any) {
console.log(`Client disconnected: ${client.id}`);
}
@SubscribeMessage('message')
handleMessage(client: any, payload: { text: string }) {
this.server.emit('message', payload);
}
}
Step 5: Register the Gateway
Next, you need to register the gateway in your application module. Open app.module.ts
and add the ChatGateway
:
import { Module } from '@nestjs/common';
import { ChatGateway } from './chat.gateway';
@Module({
imports: [],
providers: [ChatGateway],
})
export class AppModule {}
Step 6: Create a Frontend to Connect
For the frontend, you can use any framework or plain HTML/JavaScript. Here’s a simple example using plain HTML and JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat App</title>
<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
</head>
<body>
<input id="message" placeholder="Type a message" />
<button onclick="sendMessage()">Send</button>
<ul id="messages"></ul>
<script>
const socket = io('http://localhost:3000');
socket.on('message', function (data) {
const li = document.createElement('li');
li.appendChild(document.createTextNode(data.text));
document.getElementById('messages').appendChild(li);
});
function sendMessage() {
const input = document.getElementById('message');
socket.emit('message', { text: input.value });
input.value = '';
}
</script>
</body>
</html>
Step 7: Run Your Application
Start your NestJS server by running:
npm run start
Open the HTML file in multiple browser tabs to test the real-time chat functionality. You should see messages being sent and received in real time!
Code Optimization Tips
- Namespace and Rooms: Use namespaces and rooms in Socket.IO for better organization and scalability.
- Error Handling: Implement error handling in your WebSocket events to enhance user experience.
- Performance Monitoring: Utilize tools like
pm2
to monitor performance in production environments.
Troubleshooting Common Issues
- CORS Issues: If you face CORS issues, ensure that your WebSocket server is configured to allow requests from your frontend.
- Connection Errors: Verify that your server is running and that the URL used in the frontend matches the server’s URL.
Conclusion
Building real-time applications using NestJS and WebSockets is a powerful way to enhance user engagement. With just a few steps, you can set up a simple chat application and explore the possibilities of real-time communication. By leveraging the strengths of NestJS and Socket.IO, you can create scalable and efficient applications tailored to your needs. Whether you are building chat apps, collaborative tools, or live notifications, the combination of NestJS and WebSockets is a formidable choice in your development toolkit. Happy coding!