NestJS is a popular framework for building scalable and efficient server-side applications. It is built on top of Node.js and provides a modular architecture that enables developers to easily create complex applications. One of the key features of NestJS is its support for WebSockets, which allows developers to build real-time applications that can send and receive data instantly.
In this article, we will explore how to use NestJS WebSockets with an example on Github. We will cover everything from setting up a NestJS project to creating a simple real-time chat application using WebSockets.
Setting Up a NestJS Project
The first step to using NestJS WebSockets is to set up a new NestJS project. You can do this by using the Nest CLI, which is a command-line interface for NestJS. To install the Nest CLI, run the following command:
$ npm install -g @nestjs/cli
Once you have installed the Nest CLI, you can create a new NestJS project by running the following command:
$ nest new my-project
This will create a new NestJS project in a directory called “my-project”. You can navigate to this directory by running:
$ cd my-project
Adding WebSockets to NestJS
Now that we have a new NestJS project set up, we can add support for WebSockets. NestJS provides a module called “@nestjs/websockets” that makes it easy to add WebSockets to your application. To install this module, run the following command:
$ npm install –save @nestjs/websockets
Once you have installed the “@nestjs/websockets” module, you can import it into your NestJS application by adding the following line to the “app.module.ts” file:
import { WebSocketModule } from '@nestjs/websockets';@Module({imports: [WebSocketModule],})export class AppModule {}
This will enable WebSockets support in your NestJS application.
Creating a Simple Real-time Chat Application
Now that we have set up our NestJS project and added support for WebSockets, we can start building a real-time chat application. We will create a simple chat application that allows users to send messages to each other in real-time.
First, we need to create a WebSocket server that will handle incoming connections and messages. To do this, we can create a new file called “chat.gateway.ts” in the “src” directory with the following contents:
import { WebSocketGateway, WebSocketServer, SubscribeMessage } from '@nestjs/websockets';import { Server } from 'socket.io';@WebSocketGateway()export class ChatGateway {@WebSocketServer() server: Server;
@SubscribeMessage('message')handleMessage(client: any, payload: any): void {this.server.emit('message', payload);}}
This creates a new WebSocket gateway that listens for incoming connections and messages. The “@WebSocketGateway()” decorator tells NestJS that this is a WebSocket gateway, and the “@WebSocketServer()” decorator tells NestJS to inject the WebSocket server instance into the “server” property of the class.
The “@SubscribeMessage(‘message’)” decorator tells NestJS to listen for messages with the “message” event name. When a message is received, the “handleMessage” method is called, which then broadcasts the message to all connected clients using the “server.emit()” method.
Next, we need to modify the “app.module.ts” file to include the “ChatGateway” class:
import { Module } from '@nestjs/common';import { WebSocketModule } from '@nestjs/websockets';import { ChatGateway } from './chat.gateway';@Module({imports: [WebSocketModule],providers: [ChatGateway],})export class AppModule {}
This tells NestJS to include the “ChatGateway” class as a provider, which will allow it to be injected into other parts of the application.
Finally, we can create a simple client that connects to the WebSocket server and sends messages. We can create a new file called “main.ts” with the following contents:
import * as io from 'socket.io-client';const socket = io('http://localhost:3000');
socket.on('connect', () => {console.log('Connected to server');});
socket.on('message', (data: any) => {console.log('Received message:', data);});
setInterval(() => {socket.emit('message', { text: 'Hello, world!' });}, 1000);
This creates a new WebSocket client that connects to the server and sends a message every second. The “socket.on(‘connect’)” event is fired when the client connects to the server, and the “socket.on(‘message’)” event is fired when a message is received from the server.
Conclusion
In this article, we have explored how to use NestJS WebSockets with an example on Github. We have covered everything from setting up a NestJS project to creating a simple real-time chat application using WebSockets.
NestJS WebSockets provide a powerful way to build real-time applications that can send and receive data instantly. With the help of the “@nestjs/websockets” module, it is easy to add WebSockets support to your NestJS application.
FAQ
- What is NestJS?
- What are WebSockets?
- What is the “@nestjs/websockets” module?
- What is a WebSocket gateway?
NestJS is a popular framework for building scalable and efficient server-side applications. It is built on top of Node.js and provides a modular architecture that enables developers to easily create complex applications.
WebSockets are a protocol for real-time communication between a client and a server. They allow the server to push data to the client instantly, without the need for the client to constantly request new data.
The “@nestjs/websockets” module is a module provided by NestJS that makes it easy to add WebSockets support to your application. It provides a set of decorators and classes that simplify the creation of WebSocket gateways and clients.
A WebSocket gateway is a class in NestJS that listens for incoming WebSocket connections and messages. It provides a set of methods that can be used to handle incoming messages and broadcast messages to connected clients.