,

[Code Sharing] Real-Time Messaging Application with ReactJS, ExpressJS, MongoDB, and Socket.IO (2024)

Posted by


In this tutorial, we will create a real-time messaging application using ReactJS for the frontend, ExpressJS for the backend, MongoDB as the database, and Socket.IO for real-time communication. This application will allow users to send and receive messages in real-time.

Prerequisites:

  • Basic knowledge of ReactJS, ExpressJS, MongoDB, and Socket.IO
  • Node.js installed on your machine
  • MongoDB installed on your machine

Step 1: Set up the backend with ExpressJS and MongoDB
First, let’s set up the backend of our application using ExpressJS and MongoDB. Create a new directory for your project and run the following commands:

$ mkdir real-time-messaging-app
$ cd real-time-messaging-app
$ npm init -y
$ npm install express mongoose

Next, create a new file called server.js and add the following code:

const express = require('express');
const mongoose = require('mongoose');

const app = express();
const PORT = process.env.PORT || 5000;

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/real-time-messaging', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

mongoose.connection.on('connected', () => {
  console.log('Connected to MongoDB');
});

// Define routes
app.use('/api/messages', require('./routes/messages'));

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

Create a new folder called routes and inside it, create a new file called messages.js. Add the following code to define the message routes:

const express = require('express');
const router = express.Router();

const Message = require('../models/Message');

// Get all messages
router.get('/', async (req, res) => {
  try {
    const messages = await Message.find();
    res.json(messages);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// Create a new message
router.post('/', async (req, res) => {
  const message = new Message({
    text: req.body.text,
  });

  try {
    const newMessage = await message.save();
    res.status(201).json(newMessage);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

module.exports = router;

Create a new folder called models and inside it, create a new file called Message.js. Add the following code to define the message model:

const mongoose = require('mongoose');

const messageSchema = new mongoose.Schema({
  text: {
    type: String,
    required: true,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

module.exports = mongoose.model('Message', messageSchema);

Step 2: Set up the frontend with ReactJS
Next, let’s set up the frontend of our application using ReactJS. Create a new folder called client inside your project directory and run the following commands:

$ npx create-react-app client
$ cd client

Replace the contents of the src/App.js file with the following code:

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

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

const App = () => {
  const [messages, setMessages] = useState([]);
  const [newMessage, setNewMessage] = useState('');

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

    fetch('/api/messages')
      .then(res => res.json())
      .then(data => setMessages(data));
  }, []);

  const handleChange = event => {
    setNewMessage(event.target.value);
  };

  const handleSubmit = event => {
    event.preventDefault();
    socket.emit('message', newMessage);
    setNewMessage('');
  };

  return (
    <div>
      <h1>Real-time Messaging App</h1>
      <div>
        {messages.map((message, index) => (
          <div key={index}>
            <p>{message.text}</p>
          </div>
        ))}
      </div>
      <form onSubmit={handleSubmit}>
        <input type="text" value={newMessage} onChange={handleChange} />
        <button type="submit">Send</button>
      </form>
    </div>
  );
};

export default App;

Next, add the following code to the src/index.js file to set up the Socket.IO connection:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import io from 'socket.io-client';

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

ReactDOM.render(<App />, document.getElementById('root'));

Step 3: Run the application
To run the application, open two terminal windows. In the first window, navigate to the root directory of your project and run the following command:

$ node server.js

In the second window, navigate to the client directory and run the following command:

$ npm start

Visit http://localhost:3000 in your browser, and you should see the real-time messaging app up and running. You can send and receive messages in real-time with the help of Socket.IO.

That’s it! You have successfully created a real-time messaging application using ReactJS, ExpressJS, MongoDB, and Socket.IO. Feel free to customize and extend the app further to add more features and functionality.

0 0 votes
Article Rating
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@fullstack03
1 month ago

mình đã upload lại rồi nhé mọi người có thể lên tham khảo và ủng hộ mình nhé : https://doanwebsite.com/chi-tiet-source/Share-Code-Ung-dung-nhan-tin-Real-Time-bang-ReactJS-ExpressJS-MongoDB-Socket.IO-(-2024-)/5

@fullstack03
1 month ago

bạn nào đang thắc mắc gì cứ liên hệ với mình qua zalo nhé : 0899804328

@luantran3243
1 month ago

Rep ib mình nhé

@luantran3243
1 month ago

Ib mình