How to Build a Real-Time Chat App Using MERN and Socket.io
Real-time chat applications are a classic way to learn about websockets, event-driven programming, and seamless communication between frontend and backend. By combining the MERN stack (MongoDB, Express.js, React, and Node.js) with Socket.io, you can build a powerful real-time chat app with minimal effort.
📌 Why MERN + Socket.io?
MERN stack provides a unified JavaScript environment, making development faster and more consistent.
Socket.io allows real-time, bi-directional communication between client and server, perfect for instant chat updates.
📌 Setting Up the Backend
✅ 1. Initialize Express and Socket.io
In your Node.js server, set up Express and integrate Socket.io:
const express = require('express');
const http = require('http');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server, { cors: { origin: '*' } });
io.on('connection', (socket) => {
console.log('New client connected');
socket.on('sendMessage', (msg) => {
io.emit('receiveMessage', msg); // broadcast message to all clients
});
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
server.listen(5000, () => console.log('Server running on port 5000'));
✅ 2. Connect to MongoDB
Use Mongoose to store chat messages if you want persistence:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/chatdb');
📌 Setting Up the Frontend
✅ 1. Create React Components
In your React app, install Socket.io client:
npm install socket.io-client
✅ 2. Connect to the Socket
In your chat component:
import { useEffect, useState } from 'react';
import io from 'socket.io-client';
const socket = io('http://localhost:5000');
function Chat() {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
useEffect(() => {
socket.on('receiveMessage', (msg) => {
setMessages((prev) => [...prev, msg]);
});
}, []);
const sendMessage = () => {
if (input.trim() !== '') {
socket.emit('sendMessage', input);
setInput('');
}
};
return (
<div>
<h2>Real-Time Chat</h2>
<div>
{messages.map((msg, idx) => <p key={idx}>{msg}</p>)}
</div>
<input value={input} onChange={(e) => setInput(e.target.value)} />
<button onClick={sendMessage}>Send</button>
</div>
);
}
export default Chat;
📌 Conclusion
By combining MERN and Socket.io, you can build a fully functional, real-time chat application where messages are instantly sent and received without page reloads. This setup is also easily extendable for advanced features like chat rooms, private messaging, typing indicators, and message persistence with MongoDB.
Learn MERN Stack Training Course
Read More:
Building a To-Do App Using MERN Stack
Authentication in MERN Stack Using JWT
React Router DOM: Simplifying Navigation
Using Axios to Handle API Requests in React
Visit Quality Thought Training Institute
Comments
Post a Comment