Building a Real-Time Chat App with MERN & Socket.io
This guide walks you through building a real-time chat application using the MERN stack (MongoDB, Express, React, Node.js) combined with Socket.io for real-time communication.
1. Architecture Overview
Tech Stack
Frontend: React
Backend: Node.js + Express
Database: MongoDB
Real-Time Engine: Socket.io
Auth (optional): JWT
Styling (optional): Tailwind / CSS / Material UI
High-Level Flow
React UI ↔ Socket.io Client
↕
Node.js + Express
↕
MongoDB
2. Project Setup
Folder Structure
chat-app/
├── client/ # React frontend
└── server/ # Node.js backend
3. Backend Setup (Node.js + Express + Socket.io)
Step 1: Initialize Backend
mkdir server && cd server
npm init -y
npm install express socket.io cors mongoose
Step 2: Create Server (index.js)
const express = require("express");
const http = require("http");
const { Server } = require("socket.io");
const cors = require("cors");
const app = express();
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
cors: { origin: "http://localhost:3000" }
});
io.on("connection", (socket) => {
console.log("User connected:", socket.id);
socket.on("send_message", (data) => {
io.emit("receive_message", data);
});
socket.on("disconnect", () => {
console.log("User disconnected:", socket.id);
});
});
server.listen(5000, () => {
console.log("Server running on port 5000");
});
4. Frontend Setup (React + Socket.io Client)
Step 1: Create React App
npx create-react-app client
cd client
npm install socket.io-client
Step 2: Connect to Socket Server (App.js)
import { useEffect, useState } from "react";
import io from "socket.io-client";
const socket = io("http://localhost:5000");
function App() {
const [message, setMessage] = useState("");
const [chat, setChat] = useState([]);
const sendMessage = () => {
socket.emit("send_message", { message });
setMessage("");
};
useEffect(() => {
socket.on("receive_message", (data) => {
setChat((prev) => [...prev, data]);
});
}, []);
return (
<div>
<h2>Real-Time Chat</h2>
<input
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<button onClick={sendMessage}>Send</button>
{chat.map((msg, i) => (
<p key={i}>{msg.message}</p>
))}
</div>
);
}
export default App;
5. Adding MongoDB for Message Persistence
Step 1: Define Message Schema
const mongoose = require("mongoose");
const MessageSchema = new mongoose.Schema({
message: String,
sender: String,
timestamp: { type: Date, default: Date.now }
});
module.exports = mongoose.model("Message", MessageSchema);
Step 2: Save Messages in Socket Event
socket.on("send_message", async (data) => {
const newMessage = new Message(data);
await newMessage.save();
io.emit("receive_message", data);
});
6. Adding Rooms & Private Chats
Join a Room
socket.on("join_room", (room) => {
socket.join(room);
});
Send Message to Room
socket.to(room).emit("receive_message", data);
7. Authentication (Optional)
Use JWT for user login
Attach token to socket handshake
Validate token before allowing connection
8. Deployment Considerations
Backend
Use PM2 or Docker
Enable CORS correctly
Secure Socket.io with authentication
Frontend
Build React app (npm run build)
Serve via Nginx or Vercel
9. Performance & Scaling
Use Redis Adapter for Socket.io scaling
Load balancing with sticky sessions
Store messages efficiently with indexes
10. Common Features to Add
Typing indicators
Read receipts
Online/offline status
File & image sharing
Push notifications
11. Common Pitfalls
Not handling socket cleanup
Emitting to all users instead of rooms
No authentication on sockets
Storing too many messages in memory
✅ Final Summary
By combining the MERN stack with Socket.io, you can build a scalable, real-time chat application that supports instant messaging, persistence, and live updates. Socket.io handles real-time communication, while MERN provides a robust foundation for full-stack development.
Learn MERN Stack Training in Hyderabad
Read More
๐ก Projects & Tutorials in MERN
Working with Environment Variables in Production
Using Git Hooks for Code Quality
Visit Our Quality Thought Training Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments