Building a Real-time Chat App with React, Node.js, Socket.io, MongoDB, and Group Chats

Posted by

In this tutorial, we will learn how to create a realtime responsive chat app using React for the frontend, Node.js for the backend, Socket.io for real-time communication, and MongoDB for storing our chat data. Additionally, we will implement group chats functionality within our chat app.

Prerequisites:
Before starting this tutorial, you should have a basic understanding of React, Node.js, Socket.io, MongoDB, and JavaScript. You should also have Node.js and MongoDB installed on your machine.

Step 1: Setting up the Node.js backend
Firstly, let’s create a new Node.js project. Open your terminal and run the following commands:

mkdir chat-app
cd chat-app
npm init -y

Next, let’s install the necessary dependencies for our backend server:

npm install express socket.io mongoose body-parser

Once the dependencies are installed, create a new file named server.js in the root directory of your project and add the following code:

const express = require("express");
const socketio = require("socket.io");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");

const app = express();
const server = require("http").createServer(app);
const io = socketio(server);

mongoose.connect("mongodb://localhost/chatApp", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

app.use(bodyParser.json());

// Define your routes here

const PORT = 5000;
server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

In the above code snippet, we have set up an Express server, connected to a MongoDB database, and initialized Socket.io for real-time communication. Don’t forget to add your own routes for handling chat functionality.

Step 2: Creating the React frontend
To create the React frontend, open a new terminal window and run the following commands:

npx create-react-app chat-frontend
cd chat-frontend

Next, install the socket.io client library by running:

npm install socket.io-client

Now, open the src directory in your React project and create a new file named Chat.js. Add the following code to create a basic chat component:

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

const Chat = () => {
  const [messages, setMessages] = useState([]);
  const [message, setMessage] = useState("");
  const socket = io("http://localhost:5000");

  useEffect(() => {
    socket.on("message", (message) => {
      setMessages([...messages, message]);
    });

    return () => {
      socket.disconnect();
    };
  }, [messages]);

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

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

export default Chat;

This code snippet sets up a basic chat component that sends and receives messages via Socket.io.

Step 3: Implementing group chat functionality
To implement group chats in our chat app, we need to modify our backend server to handle multiple chat rooms.

Add the following code to your server.js to create a chat room for group chats:

const chatRooms = {};

io.on("connection", (socket) => {
  socket.on("joinRoom", (room) => {
    if (!chatRooms[room]) {
      chatRooms[room] = [];
    }
    chatRooms[room].push(socket);

    socket.on("message", (message) => {
      chatRooms[room].forEach((s) => {
        if (s !== socket) {
          s.emit("message", message);
        }
      });
    });

    socket.on("disconnect", () => {
      const index = chatRooms[room].indexOf(socket);
      if (index !== -1) {
        chatRooms[room].splice(index, 1);
      }
    });
  });
});

In the above code, we maintain a list of chat rooms where each room is an array of sockets that have joined the room. We broadcast messages to all sockets in a particular room except for the sender.

To use the group chat functionality in our React frontend, we need to update the Chat.js component as follows:

const Chat = () => {
  const [messages, setMessages] = useState([]);
  const [message, setMessage] = useState("");
  const [room, setRoom] = useState("general");
  const socket = io("http://localhost:5000");

  useEffect(() => {
    socket.emit("joinRoom", room);

    socket.on("message", (msg) => {
      setMessages([...messages, msg]);
    });

    return () => {
      socket.disconnect();
    };
  }, [messages, room]);

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

  return (
    <div>
      <select onChange={(e) => setRoom(e.target.value)}>
        <option value="general">General</option>
        <option value="tech">Tech</option>
      </select>
      <ul>
        {messages.map((msg, idx) => (
          <li key={idx}>{msg}</li>
        ))}
      </ul>
      <input
        type="text"
        value={message}
        onChange={(e) => setMessage(e.target.value)}
      />
      <button onClick={sendMessage}>Send</button>
    </div>
  );
};

Now, you have successfully implemented group chat functionality in your chat app. You can create multiple chat rooms and switch between them using the dropdown menu.

Conclusion:
In this tutorial, we have created a realtime responsive chat app with React, Node.js, Socket.io, and MongoDB. We have also implemented group chat functionality within our chat app. Now you can further enhance your chat app by adding features like user authentication, file uploads, and message encryption. Happy coding!

0 0 votes
Article Rating
20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@vishnubhanavath2008
2 months ago

Very good tutorial but I have a small request for you Insted of writing the entire code, please make videos on how you think as a developer and how you design a system and database. We are only coping the code you are writing, so please teach us about how to think like you as a developer.

@reactnativetypescriptbuilds
2 months ago

Thanks for great tut. I'm Suggesting that before we start writing the css, please elaborate on what we want to achieve so we have a mental modal. Thanks

@dgDurgesh
2 months ago

Sir please tell me can I deploy it on any free platform like vercel or render etc.
please give me the some process steps here.
what should I have to do??
please! '🙏🙏🙏🙏🙏🙏🙏🙏

@kamranali-hq7kv
2 months ago

Webrtc pa aik tutorial bano plz

@bridgenapp
2 months ago

Hello Kishan, your videos are awesome even for a newbie. You have inspired me to work on a project that I'm very pationate with since I came across your videos.
One last question though, you can choose to answer me on DM. Are you working for any startup? If not, are you open for one?

@Azeem_Idrisi
2 months ago

Just started with this tutorial and man the VSCode tips you are giving is just awesome. I already know most of them but still there are few which I didn’t know.

Your way of explanation is also very cool.

Thank you for teaching us with good coding practices and great tricks which every beginner must know.

Keep it up, lots of love ❤
Wishing you luck ✨

@ayushvadiya1486
2 months ago

can you show your database set5

@FinanceMaster_07
2 months ago

Please clone any stock market broker website just like grow, upstock and angle-one etc.
So that we learn how to manage financial web application.
Because no one teach this every one clone youtube, chating app no one clone financial web application please make

@manmohitsingh1180
2 months ago

How can you add " Emmet Abbreviation " you just type ( .flex ) and after that they will show proper <div> code at 2:10:50 Please let me know .

@vitorsanto1479
2 months ago

Hello, good morning. Could you help me? I have a project similar to yours, but I stalled after logging in and registering.

I made a user table with user_id, email, and password (with hash, bcrypt). And authenticated with jwt.

I would like my registered users to make posts and these posts to be stored in the database with the user id and email in another table. And then returned to an endpoint. Could you give me some help on how to do this?

@stavroskefaleas6320
2 months ago

Excellent video.
I can't make prettier wrap the tailwind classes over at least a second line.
Any ideas?

@ashishpatil5099
2 months ago

Have you provide the reactjs coures realtime

@Hellsa352
2 months ago

hi bhaiya bhaiya can you please create chat app in kotlin jetpack compose , with backend in nodejs socket io , express please please bhaiya 😭😭😭

@abhishekcode
2 months ago

Thanks brother🎉

@vishnubhanavath2008
2 months ago

Why do we use redux or zustand even if we have usecontext api in react

@truongbuipv
2 months ago

add features seen and active status will be better

@cybertaco3602
2 months ago

We finally got a recent 2024 one! This is incredibly helpful!

@playlist-d3
2 months ago

if anyone got source code please share with me

@aryankashyap9730
2 months ago

For this project do we need to buy hostinger

@Dev76194
2 months ago

any one can please their repository link plz