NestJS is a popular framework for building server-side applications with Node.js.

With its support for WebSockets, NestJS is well-suited for developing real-time chat applications.

So, what are WebSockets, and how can you build a real-time chat app in NestJS?

WebSocket client-server communication visualization

What Are WebSockets?

WebSockets are a protocol for persistent, real-time, and two-way communication between a client and a server.

Learning aboutWebSockets in JavaScripthelps to understand the concept even better.

Building a Real-Time Chat API Using the NestJS WebSocket Module

Node.js provides two major WebSockets implementations.

The first iswswhich implements bare WebSockets.

And the second one issocket.io, which provides more high-level features.

NestJS has modules for bothsocket.ioandws.

This article uses thesocket.iomodule for the sample app’s WebSocket features.

The code used in this project is available in aGitHub repository.

The command generates a new directory that contains the project files.

Now you’re ready to start the development process.

Copy the URL and store it as theMONGO_URIvariable in your.envfile.

You would also be needing Mongoose later on when you make queries to MongoDB.

Install it by runningnpm install mongoosein your terminal.

In thesrcfolder, create a file calledmongo.config.tsand paste the following code into it.

This can be done by running the following command in the terminal.

Create achat.gateway.tsfile inside thechatsfolder, this is where the gateway that sends and receives messages is implemented.

Paste the following code intochat.gateway.ts.

This makes it possible to receive messages and information about the currently connected user.

Below is an implementation of services to create a new message and get all messages inchats.service.ts.

TheMessageDtois implemented in amessage.dto.tsfile in thedtofolder in thechatsdirectory.

you’re free to also find it in the repository.

you gotta add themessagemodel and schema to the list of imports inchats.module.ts.