10-building-a-real-time-chat-application-using-nestjs-and-websockets.html

Building a Real-Time Chat Application Using NestJS and WebSockets

Creating a real-time chat application is an exciting project that showcases the power of modern web technologies. With the rise of instant messaging and collaborative platforms, having a solid understanding of how to implement real-time communication is invaluable. In this article, we will guide you through building a real-time chat application using NestJS and WebSockets. We’ll cover definitions, use cases, coding examples, and step-by-step instructions to help you create your own chat application.

What is NestJS?

NestJS is a progressive Node.js framework that helps developers build efficient and scalable server-side applications. It leverages TypeScript and is built around the concepts of modularity and dependency injection, making it an excellent choice for building robust applications. With its powerful features and easy scalability, NestJS is ideal for creating real-time applications.

What are WebSockets?

WebSockets are a communication protocol that enables persistent, bidirectional communication between a client and a server. Unlike traditional HTTP requests, which are unidirectional and stateless, WebSockets allow for continuous data exchange, making them perfect for real-time applications like chat apps or collaborative tools.

Use Cases for Real-Time Chat Applications

  • Social Media: Enabling real-time interactions among users.
  • Customer Support: Providing instant feedback and assistance through live chat.
  • Team Collaboration: Facilitating communication among team members in project management tools.
  • Online Gaming: Enabling real-time communication between players.

Getting Started

Prerequisites

Before diving into code, ensure you have the following installed:

  • Node.js (version 14 or above)
  • npm (Node package manager)
  • A code editor (like Visual Studio Code)

Setting Up Your NestJS Project

  1. Create a new NestJS project:

bash npm i -g @nestjs/cli nest new chat-app cd chat-app

  1. Install WebSocket dependencies:

bash npm install @nestjs/websockets socket.io

Building the Chat Module

Step 1: Create a Chat Module

Generate a new module for handling chat functionality.

nest generate module chat

Step 2: Create a Chat Gateway

A gateway is responsible for handling WebSocket connections and events.

nest generate gateway chat/chat

Open chat.gateway.ts and implement the following code:

import {
  WebSocketGateway,
  WebSocketServer,
  SubscribeMessage,
  OnGatewayInit,
  Socket,
  Server,
} from '@nestjs/websockets';
import { MessageBody } from '@nestjs/common';

@WebSocketGateway()
export class ChatGateway implements OnGatewayInit {
  @WebSocketServer() server: Server;

  afterInit(server: Server) {
    console.log('WebSocket Server Initialized');
  }

  @SubscribeMessage('message')
  handleMessage(@MessageBody() data: { sender: string; message: string }): void {
    this.server.emit('message', data);
  }
}

Step 3: Set Up the Chat Module

In chat.module.ts, import your gateway:

import { Module } from '@nestjs/common';
import { ChatGateway } from './chat.gateway';

@Module({
  providers: [ChatGateway],
})
export class ChatModule {}

Step 4: Integrate Chat Module into the Application

Edit app.module.ts to include the ChatModule:

import { Module } from '@nestjs/common';
import { ChatModule } from './chat/chat.module';

@Module({
  imports: [ChatModule],
})
export class AppModule {}

Step 5: Running the Application

To start your application, run:

npm run start

Your WebSocket server is now up and running!

Frontend Setup

For our example, let’s create a simple HTML and JavaScript front end to connect to our WebSocket server.

Step 1: Create an index.html File

Create an index.html file at the root of your project:

<!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>
</head>
<body>
    <input id="message" placeholder="Type a message" />
    <button onclick="sendMessage()">Send</button>
    <ul id="messages"></ul>

    <script src="/socket.io/socket.io.js"></script>
    <script>
        const socket = io();

        socket.on('message', function(data) {
            const messages = document.getElementById('messages');
            const newMessage = document.createElement('li');
            newMessage.textContent = `${data.sender}: ${data.message}`;
            messages.appendChild(newMessage);
        });

        function sendMessage() {
            const messageInput = document.getElementById('message');
            const message = messageInput.value;
            socket.emit('message', { sender: 'User', message });
            messageInput.value = '';
        }
    </script>
</body>
</html>

Step 2: Serve the HTML File

You can use any static file server to serve this file or integrate it into your NestJS application. For simplicity, you can use the serve package:

npm install serve

Then run:

npx serve .

Testing Your Application

  1. Open multiple browser tabs to your HTML file.
  2. Type messages in one tab and watch them appear in real-time in others.

Troubleshooting Common Issues

  • WebSocket connection issues: Ensure your server is running and the client is connecting to the correct WebSocket URL.
  • CORS issues: If you encounter CORS problems, configure the WebSocket server to allow cross-origin requests.
  • Deployment: When deploying, ensure your server supports WebSocket connections, as some hosting services may restrict them.

Conclusion

Building a real-time chat application using NestJS and WebSockets is a fulfilling endeavor that enhances your coding skills and understanding of real-time communication protocols. By following the steps outlined in this article, you can create a functional chat application and explore more advanced features like authentication, message persistence, and user management. Embrace the power of real-time web applications and take your projects to the next level!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.