This section details the real-time messaging capabilities of the Chat App MERN, focusing on how messages are sent, received, and displayed instantly between users.
The backend utilizes Socket.IO to manage real-time connections and message broadcasting. The socket.js file sets up the Socket.IO server and handles user connections and disconnections. It maintains a map (userSocketMap) to store the mapping between user IDs and their corresponding socket IDs, enabling direct communication with specific users.
The sendMessage controller in message.controller.js is responsible for handling new messages. Upon receiving a message, it saves it to the database and then uses the getReceiverSocketId function to find the recipient's socket ID. If the recipient is online, the new message is emitted to their socket using the newMessage event.
On the frontend, the ChatContainer.jsx component subscribes to the newMessage event using subscribeToMessages. When a new message is received, it's added to the local state, causing the chat interface to update instantly without requiring a page refresh.
The axiosInstance from frontend/src/lib/axios.js is used to make API requests to the backend. For fetching messages, it targets the /messages/:id endpoint.