,

Developing a Real-Time Chat App Using MERN Stack with Express Application

Posted by


In this tutorial, we will be creating a real-time chat application using the MERN (MongoDB, Express, React, Node.js) stack. We will start by setting up the backend with Express, creating routes and setting up a real-time chat functionality using Socket.io. Then, we will create the frontend using React to interact with the backend.

Step 1: Setting up the backend with Express

  1. Install Express generator:
    To start, we will use the Express generator to create our backend. Install the Express generator globally using npm:

npm install -g express-generator

  1. Create a new Express project:
    Create a new Express project using the following command:

express chat-backend

This will create a new project with the necessary Express setup.

  1. Install dependencies:
    Navigate into the newly created project directory and install the necessary dependencies:

cd chat-backend
npm install

  1. Create routes for chat functionality:
    Create a new file named chatRoute.js inside the routes directory. In this file, we will define the routes for our chat functionality.
const express = require('express');
const router = express.Router();

router.get('/messages', (req, res) => {
  res.json({ messages: [] });
});

module.exports = router;
  1. Configure the Express app:
    In the app.js file, import the chat routes file and use it in the Express app:
const chatRoute = require('./routes/chatRoute');
app.use('/chat', chatRoute);

Step 2: Setting up real-time chat functionality with Socket.io

  1. Install Socket.io:
    Install Socket.io and Socket.io-client dependencies using npm:

npm install socket.io socket.io-client

  1. Configure Socket.io in Express:
    In the app.js file, require the http module and create a new instance of the HTTP server. Then, create a Socket.io instance and pass the server as an argument:
const http = require('http').createServer(app);
const io = require('socket.io')(http);

io.on('connection', (socket) => {
  console.log('A user connected!');
});

http.listen(3001, () => {
  console.log('Socket.io server running on port 3001');
});
  1. Implement real-time chat functionality:
    Inside the io.on('connection') event, we will implement the logic for handling real-time messages. Emit events for sending and receiving messages.
io.on('connection', (socket) => {
  console.log('A user connected!');

  socket.on('chat message', (msg) => {
    io.emit('chat message', msg);
  });
});

Step 3: Setting up the Frontend with React

  1. Create a new React project:
    Create a new React project using create-react-app:

npx create-react-app chat-frontend

  1. Install Socket.io-client:
    Install Socket.io-client in the React project:

npm install socket.io-client

  1. Create a chat component:
    Create a new component named Chat inside the src/components directory. Implement the logic for sending and receiving messages using Socket.io-client.
import React, { useEffect, useState } from 'react';
import io from 'socket.io-client';

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

const Chat = () => {
  const [messages, setMessages] = useState([]);
  const [message, setMessage] = useState('');

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

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

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

export default Chat;
  1. Render the chat component in the App component:
    Import the Chat component and render it inside the App component in the src/App.js file.
import React from 'react';
import Chat from './components/Chat';

function App() {
  return (
    <div>
      <Chat />
    </div>
  );
}

export default App;
  1. Run the application:
    Run both the Express backend and React frontend using the following commands:

For the backend:
npm start

For the frontend:
npm start

You should now have a real-time chat application up and running using the MERN stack! Users can send and receive messages in real-time using Socket.io. Happy coding!

0 0 votes
Article Rating

Leave a Reply

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@paramasivanb8903
14 days ago

he is provide a Quality content, but this channel is being underrated its hurt now

@AkashAhmed-i1x
14 days ago

Why i can not access next videos

@shadowsees5673
14 days ago

please complete your nestjs series

@SaiKumar-tg6ct
14 days ago

Anna, can you please make videos docker & kubernates

4
0
Would love your thoughts, please comment.x
()
x