π¬ Real-Time Chat Application (MERN + Socket.IO)
A full-stack real-time chat application built with React, Node.js, Express, MongoDB, and Socket.IO. It supports authentication, real-time messaging, unread message tracking, and online presence detection.
** Features -- JWT Authentication -- Real-time messaging with Socket.IO -- Online / Offline user tracking -- Unread message count per user -- Message seen/read status -- Instant UI updates -- Clean architecture (REST + WebSockets) -- Secure & scalable backend
Frontend - React, Context API, Axios, Socket.IO Client, Tailwind CSS Backend - Node.js, Express.js, MongoDB & Mongoose, Socket.IO, JWT Authentication
Client (React) β HTTP Server (Node.js) β Express (REST API) β MongoDB (Database) β Socket.IO (Real-time Layer)
Messaging Logic -- Fetch Users -- Returns all users except logged-in user -- Excludes passwords -- Includes unread message count USER.find({ _id: { $ne: userId } }).select("-password");
Unread Messages Logic MESSAGE.find({ senderId: user._id, receiverId: userId, seen: false }); β Counts only unread messages β Used for sidebar badges
π Real-Time Messaging (Socket.IO) *** Why Socket.IO? -- REST handles data -- Socket.IO handles real-time events
Connection Flow User connects β socket.id assigned β stored in userSocketMap β online status updated
Online Users Tracking const userSocketMap = { userId: socketId }; Used for: Online indicators, Private messaging, Presence updates
π© Message Flow When a message is sent: -- REST API saves message -- Socket emits message -- Receiver gets it instantly -- UI updates in real time
β‘ Socket Lifecycle io.on("connection", socket => { // user connects });
socket.on("disconnect", () => { // user disconnects }); β Tracks online users β Cleans up on disconnect β Prevents stale sockets
π§ Frontend State Management AuthContext: User authentication, Token handling, Socket connection, Online users Chat State: Selected user, Messages, Unread message count, Real-time updates
β¨οΈ UX Enhancements -- Press Enter to send message -- Auto-scroll chat -- Live unread badges -- Real-time updates -- Online indicators
π Future Improvements -- Typing indicators -- Group chats -- File sharing -- Message reactions -- Push notifications -- Read receipts
Author
Akano Olayiwola Full-Stack Developer
πΌ MERN Stack π¬ Real-time Systems β‘ Scalable Applications