Real-time Messaging
Relevant source files
The following files were used as context for generating this wiki page:
The Real-time Messaging feature provides a direct communication channel between users (buyers) and sellers within the e-commerce platform. This system is built using a combination of a dedicated Socket.io server for real-time event handling, a backend API for message persistence and conversation management, and React components for the user interface. This allows for instant messaging, including text and images, to facilitate customer support and pre-sale inquiries.
The architecture is decoupled, with a separate socket directory containing the real-time server, a backend for handling RESTful API requests, and a frontend that consumes both services. This separation ensures scalability and maintainability of the chat functionality.
Sources: README.md, backend/app.js, frontend/src/pages/UserInbox.jsx
Architecture Overview
The messaging system consists of three primary components: the Frontend Client, the Backend API Server, and a dedicated Socket.io Server. They work in concert to deliver a seamless real-time chat experience.
- Frontend Client (React): Renders the chat UI for both users (
UserInbox.jsx) and sellers (DashboardMessages.jsx). It establishes a persistent WebSocket connection to the Socket.io Server for real-time updates and makes HTTP requests to the Backend API to fetch historical data or create new conversations and messages. - Backend API Server (Node.js/Express): Exposes REST endpoints for creating conversations, sending messages, and retrieving message history. It is responsible for all database interactions, ensuring that chat data is persisted.
- Socket.io Server (Node.js): Manages WebSocket connections, tracks online users, and relays messages between connected clients in real-time. It does not interact directly with the database; its role is to facilitate instant communication.
The following diagram illustrates the high-level interaction between these components.
Backend Components
The backend is responsible for data persistence and providing a RESTful API for the messaging feature.
Sources: backend/app.js, backend/controller/message.js
API Endpoints
The messaging functionality is exposed through the /api/v2/message and /api/v2/conversation routes.
| Method | Endpoint | Description |
|---|---|---|
POST | /api/v2/message/create-new-message | Creates and saves a new message to a conversation. It handles both text and image uploads (multipart/form-data). |
GET | /api/v2/message/get-all-messages/:id | Retrieves all messages for a given conversation ID. |
POST | /api/v2/conversation/create-new-conversation | Initiates a new conversation between a user and a seller, typically from a product page. |
PUT | /api/v2/conversation/update-last-message/:id | Updates the lastMessage and lastMessageId fields of a conversation to display a preview in the conversation list. |
Sources: backend/app.js:71-72, backend/controller/message.js:10-40, 44-56, frontend/src/components/Products/ProductDetails.jsx:62-70, frontend/src/components/Shop/DashboardMessages.jsx:150-161
Data Model
Messages are stored in the database using the Messages model. The structure is inferred from its usage in the controller.
The diagram below shows the entity relationship for the messages table.
Sources: backend/controller/message.js:19-25
Socket Server
The Socket.io server, located in the /socket directory, is the core of the real-time functionality. It manages user presence and message broadcasting.
Socket Events
The client and server communicate using a set of predefined events.
| Event Name | Emitter | Listener(s) | Description |
|---|---|---|---|
addUser | Client | Server | A user or seller connects and sends their ID to be added to the list of online users. |
getUsers | Server | Client | The server sends the current list of online users to the connected client. |
sendMessage | Client | Server | A client sends a message payload (including text or images and receiver ID) to the server. |
getMessage | Server | Client | The server forwards the received message to the intended recipient client. |
updateLastMessage | Client | Server | A client sends an event to notify that the last message of a conversation has been updated. |
newMsg | Server | Client | A generic event emitted by the backend via io.emit() to signal clients to refetch message/conversation data. |
Sources: frontend/src/components/Shop/DashboardMessages.jsx:43-49, 75-81, 131-137, frontend/src/pages/UserInbox.jsx:38-44, 131-137, backend/controller/message.js:27
Frontend Implementation
The frontend contains several React components that together form the chat interface for both users and sellers.
Initiating a Conversation
A user can start a conversation with a seller directly from a product details page. The handleMessageSubmit function is triggered when the "Send a message" button is clicked.
This function performs a POST request to /api/v2/conversation/create-new-conversation with the user ID and seller ID. Upon successful creation of the conversation, the user is redirected to their inbox page (/inbox) with the new conversation ID in the URL query string.
Sources: frontend/src/components/Products/ProductDetails.jsx:62-74
User & Seller Inbox
Both the user inbox (UserInbox.jsx) and the seller's message dashboard (DashboardMessages.jsx) share a similar structure and logic.
- State Management: They use
useStateto manage conversations, messages, and the currently active chat. - Data Fetching:
useEffecthooks are used to fetch all conversations for the logged-in user/seller and the messages for the selected conversation via API calls. - Socket Connection: They establish a connection to the Socket.io server, register the user with
addUser, and set up listeners forgetMessageandgetUsersto update the UI in real-time. - Sending Messages: The
sendMessageHandlerfunction handles form submission. It optimistically updates the local state, emits asendMessageevent to the socket server, and sends aPOSTrequest to the backend API to persist the message. It also handles image uploads by sendingmultipart/form-data.
Sources: frontend/src/pages/UserInbox.jsx, frontend/src/components/Shop/DashboardMessages.jsx
Data Flow: Sending a Message
The sequence diagram below details the process of a user or seller sending a new message.
This diagram shows the dual path of a sent message: one through the WebSocket for real-time delivery and another through the HTTP API for persistence.
Sources: frontend/src/components/Shop/DashboardMessages.jsx:113-148, frontend/src/pages/UserInbox.jsx:140-167, backend/controller/message.js:10-40
Summary
The real-time messaging feature is a critical component for enhancing user-seller interaction on the platform. Its architecture, which separates the real-time event handling (Socket.io), data persistence (Express API), and presentation (React), creates a robust and scalable system. This design allows for instant communication while ensuring all chat history is reliably stored and retrievable.
Sources: README.md