image

Sep 03 2023

cover

Building a Real-Time Chat App with WebSockets, React, and NestJS

Real-time applications are everywhere—from collaborative tools to chat applications. In this blog post, we'll build a simple real-time chat application using WebSockets, React, and NestJS.


Table of Contents

  1. Introduction
  2. Setting up the NestJS Backend
  3. Setting up the React Front-end
  4. Conclusion


Introduction

The modern web is all about real-time updates. WebSockets enable real-time, full-duplex communication between the server and connected clients. We'll use NestJS for our back-end and React for our front-end.


Setting up the NestJS Backend

First, make sure you have the NestJS CLI installed:

npm i -g @nestjs/cli

Now, create a new NestJS application:

nest new nest-chat-backend

Navigate to the newly created project directory and install the required WebSocket package:

cd nest-chat-backend npm install @nestjs/websockets @nestjs/platform-socket.io

Create a WebSocket gateway:

nest generate gateway chat

Edit chat.gateway.ts:

import { SubscribeMessage, WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

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

@SubscribeMessage('message')
handleMessage(client: Socket, payload: string): void {
this.server.emit('message', payload);
}
}



Setting up the React Front-end

Create a new React project:

npx create-react-app react-chat-frontend

Navigate to the project and install the Socket.io client:

cd react-chat-frontend npm install socket.io-client

Edit App.js:

import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';

const socket = io('http://localhost:3000');

function App() {
const [message, setMessage] = useState('');
const [chat, setChat] = useState([]);

useEffect(() => {
socket.on('message', (message) => {
setChat([...chat, message]);
});
}, [chat]);

const sendMessage = () => {
socket.emit('message', message);
setMessage('');
};

return (
<div>
<div>
{chat.map((message, i) => (
<div key={i}>{message}</div>
))}
</div>
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<button onClick={sendMessage}>Send</button>
</div>
);
}

export default App;


Conclusion

You've successfully built a real-time chat application using WebSockets with NestJS and React! This is a basic example, but it demonstrates the real-time capabilities of WebSockets and how smoothly they integrate with modern web frameworks like React and NestJS.



Happy coding!