NestJs: Chat Server in NestJs backed by MongoDB

Vikash Kumar
Jun 22 · 4 min read

This post will help you to create a Chat Server with NestJs + socket.io + MongoDB. We will develop the service in NestJs, expose the WebSocket gateway using socket.io & store the messages in MongoDB.
Follow the steps below:

Step#1: Create a NestJs project

I prefer to use Nest CLI for the same. If you do not have Nest CLI, download the package through NPM using the command:

$ npm install -g @nestjs/cli

To create a NestJs app (I am naming my project ‘chat-service’; give any name of your choice), open a console in your preferred folder, and run the command:

$ nest new chat-service
Create new NestJs project

Step#2: Create a Chat Module

Create a new NestJs Module “ChatModule”. This will create a folder ‘chat’ and a ChatModule (chat.module.ts) inside it. Run this command in terminal to generate a new module.

$ nest generate module chat
Generate Chat Module

Step#3: Add Typegoose dependencies

We will be using MongoDB for storing the chats and Typegoose for interacting with MongoDB. Install the required dependencies mentioned below:

$ npm install @typegoose/typegoose nestjs-typegoose
$ npm install mongoose@5.10.1
$ npm install --save-dev @types/mongoose@5.10.1

For more information on Typegoose integration with NestJs, visit the npm package here.

Step#4: Create a Chat entity for MongoDB

We will create a new Typegoose entity class for our ‘chat’ collection in MongoDB. We have kept just 3 columns as of now: message, sender & recipient.

Chat Entity

Step#5: Import TypegooseModule

To initialise TypegooseModule, we need a MongoDB server connection string (masked in the image below). I am using a free cloud hosted MongoDB service provided by MongoDB Atlas. Follow the steps here to obtain a free cloud hosted MongoDB service. We are here importing the TypegooseModule in the root module (AppModule -> app.module.ts).

Import TypegooseModule

Step#6: Create a ChatService

Next, we will create a ChatService (chat.service.ts) to do CRUD operations on the ‘chat’ collection through the injected Typegoose chat model. The service exposes 2 functions: getChats (to load all chats from the collection) & saveChat (to persist a single chat document).

Chat Service to interact with Typegoose

Step#7: Add socket.io dependencies

In this step, we will add the required socket.io dependencies to our application.

$ npm install @nestjs/platform-socket.io @nestjs/websockets
$ npm install --save-dev @types/socket.io

Step#8: Create a WebSocket gateway

We will now create a WebSocket gateway (chat.gateway.ts) to listen on ‘chat’ events. I have implemented the 3 lifecycle hooks provided by nestjs-socket.io: afterInit (when the service initialises), handleConnection (when a new client connect to the service) & handleDisconnect (when a client disconnects from the service).
handleNewMessage function subscribes to ‘chat’ events, receives and stores the chat in MongoDB & emits the new chat to ‘newChat’.

Chat Gateway

Step#9: Update the ChatModule

Finally, we need to provide ChatGateway & ChatService, and import the Typegoose chat model in ChatModule.

Update ChatModule

Step#10: Run the application

Now, let’s run the application. The application will run @ 3000 and so will the WebSocket.

$ npm run build
$ npm run start

Step#11: Verify

I use this amazing socket.io client to test my socket.io services. Let’s connect to our WebSocket and emit some chats. Here I am emitting a JSON object to match my Chat entity class.

Emit messages to ‘chat’

Verify if your chats are persisted to MongoDB.

Chats are persisted to MongoDB

Codebase:
https://github.com/codecaplet/NestJsTutorials/tree/master/chat-service

Nerd For Tech

From Confusion to Clarification

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Vikash Kumar

Written by

A passionate coder, technology enthusiast, tutor and continually falling in love with JavaScript. Currently exploring latest JS frameworks and Flutter.

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.