GET /api/chat (chat list with unread counts), GET /api/chat/:targetUserId (message history with pagination), PATCH /api/chat/read/:targetUserId (mark messages as read). Use Socket.io for real-time new messages and typing indicators. REST handles initial load, Socket.io handles live updates.
What REST endpoints do I need for chat?
More FAQs in Chat Message Persistence and History Loading and Paginating Messages
REST endpoint GET /api/chat/:targetUserId?page=1&limit=50. Query Message with $or for both directions, sort by createdAt -1, skip (page-1)*limit, limit. Return messages reversed (oldest first) with pagination metadata (total, totalPages, hasMore). Use compound index on (senderId, receiverId, createdAt) for efficiency.
On scroll to top, load the next page of older messages and prepend to the list. Maintain scroll position by saving the previous scrollHeight and setting scrollTop after new messages are added. Stop loading when hasMore is false.
In the message:send handler, save to MongoDB with Message.create(), update the Conversation model (lastMessage, lastMessageAt, unreadCount), then broadcast to the room via io.to(roomId).emit('message:received', message). Use a callback acknowledgment to confirm success.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.