Real-Time Chat App: instant messaging with Socket.io
A full-stack chat application where signed-in users message each other in real time and can see who is online.
- Type
- Full-stack web application
- Front end
- React, Vite, Tailwind CSS
- Back end
- Node.js, Express.js, MongoDB
- Real-time
- Socket.io
- Auth
- JWT, bcrypt
The problem
A chat is only useful if messages arrive the moment they are sent, without anyone refreshing the page. People also need to see who is available before they write. A normal request and response cycle cannot push a message to the other person, so a chat needs a live connection.
The solution
Socket.io keeps a live connection open between each signed-in browser and the Node.js server. When someone sends a message, the server saves it to MongoDB and, if the receiver is online, pushes it to them straight away. The React interface listens for a newMessage event and updates the conversation instantly.
Features
- Register and log in with JWT authentication, with passwords hashed using bcrypt
- Real-time one-to-one messaging with Socket.io
- Online and offline status for every user
- Message history stored in MongoDB
- User search in the sidebar
- Automatic scroll to the latest message
How it works
Authentication
- A new user registers, and the password is hashed before it is saved in MongoDB.
- On login the server issues a JWT, which the browser stores.
- Every API request sends the token in an
Authorization: Bearerheader. - A
protectmiddleware on the server verifies the token before any private route runs.
Real-time messaging and online status
- After login the front end connects to Socket.io with the user's id.
- The server keeps a map from each user id to their socket and shares the list of online users with every client.
- A sent message is saved to the database first, then emitted to the receiver if they are online.
- When a user disconnects they are removed from the map and the online list is sent out again.
API endpoints
POST /api/auth/registerandPOST /api/auth/loginfor sign-up and sign-inGET /api/auth/usersandGET /api/auth/mefor the user list and the current userGET /api/messages/:userIdto load a conversationPOST /api/messages/send/:receiverIdto send a message
All routes except register and login require a valid token. The code is split into a back end (models, routes, middleware and socket handling) and a front end (pages, components and a socket context), so each part is easy to find.
Read the code
The full source is on GitHub, including setup steps. If you need something similar, see my full-stack development service.
Technologies
The interface is built with React and Vite and styled with Tailwind CSS. The API runs on Node.js and Express.js, with users and messages stored in MongoDB through Mongoose. Socket.io handles the real-time layer, and JWT with bcrypt handles authentication.
Need a similar application?
Tell me what you want to build. Message me on WhatsApp or send an email.