Short answer: To build MERN stack real time applications, add Socket.IO to your Node.js and Express server, connect a Socket.IO client inside your React app, and save every important event in MongoDB. Use rooms to send updates only to the intended users, verify each connection with a token, and add Redis when you run more than one server. This setup works for chat, live order tracking, dashboards, and shared editing tools.
What Are MERN Stack Real Time Applications?
A real-time application shows new data to users within a moment of it being created, without a page refresh. When one person sends a message, places an order, or changes a value, other users see it almost at once.
A normal web app works on a request-and-response model: the browser asks, the server answers. A real-time app keeps a connection open so the server can push data to the browser whenever something changes. Real-time web application development is the work of building these live features into a website or product, from the open connection to the screen update.
Planning to become a MERN Stack developer? Follow Digittrix Academy's practical 90-day MERN Stack study plan to understand the learning roadmap, essential skills, and steps to start your full-stack development journey.
Why Choose MERN Stack Development for Real-Time Applications?
MERN stands for MongoDB, Express.js, React, and Node.js. All four parts use JavaScript, so one team can build the full product, making MERN stack real time applications easier to build and maintain.
-
Node.js handles many open connections at the same time without waiting on each one.
-
Express.js gives you routes for login, history, and file upload next to your live events.
-
MongoDB stores JSON-style documents, which match the data you send through sockets.
-
React updates only the parts of the screen that change, which suits live data.
-
One language means the same developer can write server events and screen updates.
WebSockets, Server-Sent Events and Polling in Real-Time Web Application Development
You have three main ways to send live data. Pick based on whether the browser and server must both send messages.
|
Method |
Direction |
Best for |
Weak point |
|
Polling |
Browser asks again and again |
Simple status checks |
Wastes requests, adds delay |
|
Server-Sent Events |
Server to browser only |
News feeds, price tickers |
Browser cannot send back on the same channel |
|
WebSockets |
Both ways |
Chat, games, shared editing |
Needs more care to scale |
WebSocket application development is the right path when both the browser and the server must send messages. Socket.IO is the most common choice in MERN projects. It uses WebSockets when possible, falls back to other methods when a network blocks them, and adds rooms, acknowledgments, and automatic reconnection.
Plan Before You Write Code
Write down three things before you start:
-
Events: List every message that moves between client and server, such as message:send, message:new and order:updated.
-
Rooms: Decide who should receive each event. A chat room, a single order or one user account can each be a room.
-
Source of truth: Decide that MongoDB holds the final data, and sockets only deliver changes quickly.
This plan prevents the most common problem in MERN stack real time applications: events named in different ways on the client and the server.
Step-by-Step: Build MERN Stack Real Time Applications
Step 1: Set Up the Project
Good MERN stack development starts with a clean folder split. Create two folders, server and client. In server, install express, mongoose, socket.io, jsonwebtoken, cors and dotenv. In client, create a React app and install socket.io-client. Keep the same major version of Socket.IO on both sides.
Step 2: Complete Socket.IO Integration With Express and MongoDB
Socket.IO needs the raw HTTP server, so create it from your Express app instead of calling app.listen.
js
const express = require("express");
const http = require("http");
const { Server } = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: { origin: process.env.CLIENT_URL }
});
io.on("connection", (socket) => {
socket.on("room:join", (roomId) => socket.join(roomId));
socket.on("message:send", async (data) => {
const saved = await Message.create(data);
io.to(data.roomId).emit("message:new", saved);
});
});
server.listen(5000);
The server saves the message first, then sends the saved copy, so every user sees the same data that MongoDB holds.
Step 3: Secure Every Socket Connection in Node.js Real-Time Applications
Never leave sockets open to anyone. Check a JSON Web Token when the connection starts.
js
io.use((socket, next) => {
try {
socket.user = jwt.verify(socket.handshake.auth.token, process.env.JWT_SECRET);
next();
} catch (err) {
next(new Error("Unauthorized"));
}
});
Also set the CORS origin to your real front-end address, and check on the server that a user is allowed to join a room before you call socket.join.
Step 4: Design Events and Rooms
Use clear, grouped names such as chat:message, order:status and user:typing. Send each event only to the room that needs it. A user following order 482 should not receive updates for order 483.
Keep event data small. Send an ID and the changed fields, not a full document with every nested value.
Step 5: Real-Time Data Synchronization With MongoDB Change Streams
Write to MongoDB from your event handlers or API routes. For updates from other sources, such as an admin panel or a background job, use MongoDB change streams. They notify your server when a document changes.
js
Order.watch().on("change", (change) => {
if (change.operationType === "update") {
io.emit("order:updated", change.documentKey._id);
}
});
Change streams need a replica set. MongoDB Atlas provides one by default, and you can turn a local MongoDB into a single-node replica set for testing.
Step 6: Connect the React Client
The second half of Socket.IO integration happens in React. Open the connection inside useEffect, listen for events, and close the connection when the component leaves the screen.
js
useEffect(() => {
const socket = io(API_URL, { auth: { token } });
socket.emit("room:join", roomId);
socket.on("message:new", (msg) => {
setMessages((prev) => [...prev, msg]);
});
return () => socket.disconnect();
}, [roomId]);
Load old messages from a normal REST route when the screen opens, then let the socket add new ones.
Step 7: Handle Reconnects and Weak Networks
Phones switch between Wi-Fi and mobile data, causing connections to drop. Socket.IO reconnects automatically, but your app must catch up on what it missed. Real-time data synchronization also needs a catch-up plan for users who lose their connection.
-
On reconnect, ask the server for messages newer than the last one on screen.
-
Show a small “Reconnecting” notice so users know the data may be late.
-
Give each message a client-made ID so a retry does not create a duplicate.
How to Scale MERN Stack Real Time Applications
A single server running Node.js real-time applications can handle many users, but it will reach a limit. When you run two or more servers, a user connected to server A will not receive an event emitted on server B. Fix this with:
-
Redis adapter: The @socket.io/redis-adapter package passes events between servers through Redis.
-
Sticky sessions: Set your load balancer to send each user to the same server during the connection handshake, which Socket.IO needs when long polling is allowed.
-
Stateless servers: Keep sessions in Redis or in tokens, not in server memory.
-
Nearby hosting: If most users are in India, host in a Mumbai or Delhi region to keep delay low.
Performance and Security Checklist
Use this checklist before you release MERN stack real time applications to real users.
|
Area |
What to do |
|
Authentication |
Verify a token at connection time |
|
Authorisation |
Check room access on the server |
|
Input |
Validate every event payload |
|
Rate limits |
Limit how many events one user can send per second |
|
Payload size |
Set a maximum message size |
|
Database |
Add indexes on room ID and timestamp fields |
|
Monitoring |
Log connection counts, errors and slow events |
|
Encryption |
Use HTTPS and secure WebSockets (wss://) |
Common Mistakes to Avoid
-
Sending every event to every user with io.emit instead of using rooms.
-
Trusting data from the client without checking it.
-
Keeping the only copy of data in memory, so a restart wipes it.
-
Opening a new socket on every React render, which creates many duplicate connections.
-
Skipping a plan for reconnects, so users lose messages on weak networks.
Preparing for a MERN Stack mock interview? Check out Digittrix Academy's coding practice guide to learn which programming problems to solve and how to prepare for your technical interview.
What You Can Build With This Setup
-
Chat and support tools: Team chat, customer support widgets and group messaging.
-
Live tracking: Delivery maps, ride status and order progress.
-
Dashboards: Sales counters, server health and stock levels that refresh by themselves.
-
Shared tools: Whiteboards, document editing and task boards.
-
Alerts: Booking confirmations, price changes, and system warnings.
Pick one of these for a portfolio project built on MERN stack real time applications. A chat app with login, rooms, saved history and typing status shows hiring managers that you understand sockets, databases and screen updates together.
Build Your Own MERN Stack Real Time Applications With Digittrix Academy
Reading about sockets is a good start, but hiring managers look for working projects. Digittrix Academy offers MERN stack training that covers MongoDB, Express.js, React, and Node.js. You build projects such as a live chat app and an order tracker, with Socket.IO, login, and saved data, guided step by step.
To ask about courses and admissions, email tanvi@digittrix.com, or visit Digittrix Academy.
About the author
Co-Founder: Harsh Abrol
With over 14 years of Experience in the IT Field, helping companies optimise their products for more Conversions.
Categories
MERN DevelopmentTable of Contents
- What Are MERN Stack Real Time Applications?
- Why Choose MERN Stack Development for Real-Time Applications?
- WebSockets, Server-Sent Events and Polling in Real-Time Web Application Development
- Plan Before You Write Code
-
- Step 1: Set Up the Project
- Step 2: Complete Socket.IO Integration With Express and MongoDB
- Step 3: Secure Every Socket Connection in Node.js Real-Time Applications
- Step 4: Design Events and Rooms
- Step 5: Real-Time Data Synchronization With MongoDB Change Streams
- Step 6: Connect the React Client
- Step 7: Handle Reconnects and Weak Networks
- How to Scale MERN Stack Real Time Applications
- Performance and Security Checklist
- Common Mistakes to Avoid
- What You Can Build With This Setup
- Build Your Own MERN Stack Real Time Applications With Digittrix Academy