Using WebSockets in NestJS
Last Updated :
31 Jul, 2024
WebSocket is a protocol used for real-time communication between client and server. It is a better approach to serve real-time data than short-polling and long-polling.
In this article, we will be building a simple real-time Chat Application using Socket.io which is a JavaScript library used to implement WebSocket protocol, and NestJS which is an opinionated framework to create server-side applications using TypeScript. In this article, we will also test the backend using Postman.
Steps To Create WebSockets in NestJS
Ensure that NodeJS is installed on your machine before following the below steps. Otherwise use the following guides for Windows, Linux and MacOS respectively. Launch command prompt/PowerShell/bash.
Step 1: Install NestJS as a global dependency by entering the following command:
npm install -g @nestjs/cli
Step 2: Create a nest application using the following command.
nest new websocket-demo
This will ask for the package manager for your project. Select according to your personal preference (NPM vs YARN) or choose the one which is already present in your machine.
Step 3: Install the required dependencies
npm install @nestjs/websockets @nestjs/platform-socket.io
or
yarn add @nestjs/websockets @nestjs/platform-socket.io
Also install the following Dev Dependency,
npm install -D @types/socket.io
or
yarn add -D @types/socket.io
Dependencies
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/platform-socket.io": "^10.3.10",
"@nestjs/websockets": "^10.3.10",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
"@nestjs/schematics": "^10.0.0",
"@nestjs/testing": "^10.0.0",
"@types/express": "^4.17.17",
"@types/jest": "^29.5.2",
"@types/node": "^20.3.1",
"@types/socket.io": "^3.0.2",
"@types/supertest": "^6.0.0",
"@typescript-eslint/eslint-plugin": "^7.0.0",
"@typescript-eslint/parser": "^7.0.0",
"eslint": "^8.42.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"jest": "^29.5.0",
"prettier": "^3.0.0",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.1.0",
"ts-loader": "^9.4.3",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.1.3"
}
Folder Structure
Project folder structureExample: Create a new file named app.gateway.ts inside src folder and enter the following code in it
JavaScript
//app.gateway.ts
import {
MessageBody, OnGatewayConnection,
OnGatewayDisconnect, SubscribeMessage,
WebSocketGateway, WebSocketServer
} from "@nestjs/websockets";
import { Server, Socket } from "socket.io";
@WebSocketGateway(4321)
export class AppGateway implements OnGatewayConnection,
OnGatewayDisconnect {
@WebSocketServer()
server: Server;
handleConnection(client: Socket): void {
this.server.emit('room', client.id + ' joined!')
}
handleDisconnect(client: Socket): void {
this.server.emit('room', client.id + ' left!')
}
@SubscribeMessage('customName')
handleMessage(client: Socket, message: any): void {
this.server.emit('room', `[${client.id}] -> ${message}`);
}
}
JavaScript
//app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AppGateway } from './app.gateway';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService, AppGateway],
})
export class AppModule { }
By default, the WebsSocket will be running on port 3000. If you want to change the port, then add the required port number inside the @WebSocketGateway() decorator. Here the WebSocket will be running on port 4321.
Start the application by running the following command.
npm run start
Testing
We can test our real time chat application using Postman which is a tool used to test backend systems. If Postman is not already installed in your machine, then you can find the tutorial here.
Launch Postman and create two Socket.io request to connect to our real time chat application, Enter the URL i.e. http://localhost:4321 and under events tab create a new even named "room" and toggle the respective listen button. Do this for every user which will be using our system.
When we press connect, the user can see that they have joined the room. They can also see other users who have joined after them.
To send message, type your message in the message tab of postman and also enter "customName" as event name just as shown below. We can clearly see that user 2 can see the message send by user 1.
Similarly, user 2 can talk by following the same procedure shown in the previous step.
When a user disconnects, every person in the room is notified about this action. Here user 2 leaves by disconnecting thereby informing user 1.
Output
Similar Reads
Using Mongoose with NestJS NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. It provides a solid foundation for backend development with TypeScript support, built-in decorators, and a modular architecture. Mongoose, on the other hand, is a powerful Object Data M
3 min read
Pipes in NestJS Pipes in NestJS help in transforming and validating data within your application. They play an important role in ensuring that data entering the system is clean, consistent, and meets the required criteria. In this article, we will explore how pipes work in NestJS, their benefits, and how to impleme
3 min read
Using TypeORM with NestJS NestJS is a progressive Node.js framework for building efficient and scalable server-side applications. One of the powerful features of NestJS is its ability to easily integrate with databases using TypeORM, a popular ORM (Object-Relational Mapping) tool. This article will guide you through the proc
3 min read
What is the use of WebSocket API ? API stands for Application Programming Interface. API can be defined as a predefined set of instructions that describes how different applications can communicate with one another. So one can think of API as a middleman for transferring data between a web server and the application. Every app is usi
3 min read
Chat Website using MERN Stack The "Chat Website" project is a dynamic web application that is used for real-time communication. The MERN stack, comprised of MongoDB, Express.js, React.js, and Node.js, is a powerful combination of technologies for developing robust and scalable web applications. In this article, we'll explore the
4 min read
How to Use WebSocket and Load Balancers? WebSockets are a technology that allows websites and servers to talk to each other in real time. It's like having a phone line that stays open between your browser and a server, so they can send messages back and forth quickly and efficiently without having to reconnect all the time. Important Topic
7 min read
Simple chat Application using Websockets with FastAPI In this article, we'll delve into the concept of WebSockets and their role in facilitating bidirectional communication between clients and servers. Subsequently, we'll embark on the journey of building a real-time multi-client chat application. This application will empower numerous users to connect
6 min read
Python Falcon - Websocket Websockets provide a powerful mechanism for establishing bidirectional communication between a client and a server over a single, long-lived connection. Python Falcon, a lightweight and fast web framework, offers support for implementing websockets, enabling real-time communication between clients a
3 min read
Load Balancing for WebSockets in Spring Boot WebSocket provides full-duplex communication channels over a single TCP connection, crucial for real-time applications like chat, gaming, and live data streaming. Load balancing WebSocket connections in Spring Boot ensures optimal performance and scalability by distributing incoming requests among m
4 min read
Custom Transporters in NestJS NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. One of its powerful features is the microservices architecture, which allows developers to build distributed systems. NestJS provides built-in transporters like TCP, Redis, and NATS, bu
4 min read