The Care Nexus LogoCareNexus Docs

Messaging

Real-time secure messaging between patients and doctors via Socket.IO.

Updated June 2026 5 min read

The messaging system provides secure, real-time direct messaging between patients and their doctors. It is built on Socket.IO for live delivery with MongoDB as the persistent message store and Redis caching the last 50 messages per conversation room for fast initial load. Messages are end-to-end scoped to a 1-to-1 room between a specific patient and doctor pair.

How It Works

When a patient opens the chat with a doctor for the first time, the system checks whether a conversation room already exists for that patient-doctor pair. If not, a new room is created automatically on first message send. This auto-creation means there is no "start conversation" button — the patient simply types and sends, and the room handles itself.

Socket Events

EventDirectionPayload
join-roomClient → Server{ roomId }
send-messageClient → Server{ roomId, content, type }
receive-messageServer → Client{ message object }
typingClient → Server{ roomId, userId }
stop-typingClient → Server{ roomId }
user-onlineServer → Client{ userId, isOnline }
disconnectServer → ClientAuto on connection drop

Message Persistence

Every message sent through Socket.IO is also persisted to MongoDB via the Message model. This ensures messages are not lost if either party disconnects. When a conversation is opened, the client first calls GET /api/chat/rooms/:id/messages to load historical messages, then subscribes to the Socket.IO room for new incoming messages — creating a seamless handoff between REST history and live stream.

Unread Badges

The unreadCount field on each conversation document is incremented server-side every time a message is sent to an offline recipient. When the recipient opens the conversation, a read receipt event resets the counter to zero. The sidebar and topbar badge display this count using RTK Query polling every 30 seconds as a fallback in case the socket event is missed.

Message encryption

Message content is stored encrypted in MongoDB using AES-256. The encryption key is derived from environment variables and is never sent to the client. See the Encryption docs for full details.