DEV Community

Bhavik Gevariya
Bhavik Gevariya

Posted on

Building a real-time chat application using MERN stack and Socket.IO

Real-time chat applications are becoming increasingly popular these days, and building one using the MERN stack and Socket.IO is a great way to learn how to create real-time applications. In this blog post, we'll walk through the process of building a real-time chat application from scratch.

Introduction
Socket.IO is a JavaScript library that enables real-time, bidirectional and event-based communication between the browser and the server. It works on every platform, browser, or device, focusing equally on reliability and speed. The MERN stack is a popular full-stack JavaScript framework that combines MongoDB, Express.js, React.js, and Node.js. In this tutorial, we'll be using the MERN stack and Socket.IO to build a real-time chat application.

Setting up the backend
The first step in building our real-time chat application is setting up the backend. We'll be using Node.js and Express.js to create our RESTful API and MongoDB as our database. Here are the steps to set up the backend:

  1. Install Node.js and MongoDB on your computer.
  2. Create a new folder for your project and navigate to it in your terminal.
  3. Run npm init to create a new package.json file for your project.
  4. Install the necessary dependencies by running npm install express mongoose socket.io cors dotenv.
  5. Create a new index.js file and start building your backend. In the index.js file, we'll create our server and connect to our MongoDB database using Mongoose. We'll also set up our RESTful API routes for creating and fetching messages. Here's an example:
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const dotenv = require('dotenv');
const socketio = require('socket.io');

const app = express();
const server = require('http').Server(app);
const io = socketio(server);

dotenv.config();
const port = process.env.PORT || 5000;

// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open', () => {
  console.log('MongoDB connection established successfully');
});

// Middleware
app.use(cors());
app.use(express.json());

// API Routes
const messagesRouter = require('./routes/messages');
app.use('/messages', messagesRouter);

// Start server
server.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

// Socket.IO
io.on('connection', (socket) => {
  console.log(`Socket ${socket.id} connected`);

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

  socket.on('disconnect', () => {
    console.log(`Socket ${socket.id} disconnected`);
  });
});
Enter fullscreen mode Exit fullscreen mode

Creating the frontend
Now that we have our backend set up, we can move on to creating the frontend. We'll be using React.js for our frontend and Socket.IO to enable real-time communication between the client and server. Here are the steps to create the frontend:

  1. Create a new React app by running npx create-react-app my-app in your terminal.
  2. Navigate to the newly created app directory by running cd my-app.
  3. Install the necessary dependencies by running npm install socket.io-client.
  4. Open the src/App.js file and start building your frontend. In the App.js file, we'll create a form for users to input their name and message. We'll also display the list of messages received from the server in real-time. Here's an example:
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';

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

function App() {
  const [name, setName] = useState('');
  const [message, setMessage] = useState('');
  const [messages, setMessages] = useState([]);

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

  const handleSubmit = (event) => {
    event.preventDefault();
    if (name && message) {
      socket.emit('sendMessage', { name, message });
      setName('');
      setMessage('');
    }
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input type="text" value={name} placeholder="Your name" onChange={(event) => setName(event.target.value)} />
        <input type="text" value={message} placeholder="Your message" onChange={(event) => setMessage(event.target.value)} />
        <button type="submit">Send</button>
      </form>
      <ul>
        {messages.map((message, index) => (
          <li key={index}>
            {message.name}: {message.message}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Conclusion
In this blog post, we walked through the process of building a real-time chat application using the MERN stack and Socket.IO. We started by setting up the backend with Node.js, Express.js, MongoDB, and Socket.IO. Then, we created the frontend with React.js and Socket.IO. By following this tutorial, you should have a better understanding of how to build real-time applications using the MERN stack and Socket.IO.

Image description

Small support comes a long way!

Top comments (2)

Collapse
 
abid365 profile image
Syed Jawad Bin Azam

It's just a boiler plate isn't it?

Collapse
 
bhavik786 profile image
Bhavik Gevariya

yes