Building a Real-Time Chat API with WebSocket Presence
How I built a drop-in messaging backend with JWT auth, read receipts, and online/offline presence — without depending on a third-party chat platform.
const onlineUsers = new Map();
io.on('connection', (socket) => {
socket.on('user:online', (userId) => {
onlineUsers.get(userId).add(socket.id);
io.emit('presence:update', { userId, online: true });
});
});
Every social app needs messaging. Here's how I built the Chat API to be a drop-in backend for any app needing real-time chat.
The architecture
REST for message history, WebSocket for real-time events (new messages, presence, typing indicators).
// WebSocket presence management
const onlineUsers = new Map(); // userId -> Set<socketId>io.on('connection', (socket) => { socket.on('user:online', (userId) => { if (!onlineUsers.has(userId)) onlineUsers.set(userId, new Set()); onlineUsers.get(userId).add(socket.id); io.emit('presence:update', { userId, online: true }); });
socket.on('disconnect', () => { // Remove user only if all their sockets disconnected }); }); ```
Read receipts
// Mark all messages in a thread as read
app.post('/threads/:id/read', auth, async (req, res) => {
await Message.updateMany(
{ threadId: req.params.id, readBy: { $ne: req.user.id } },
{ $push: { readBy: req.user.id } }
);
io.to(req.params.id).emit('message:read', { userId: req.user.id });
});
Why build it yourself
Third-party chat platforms are expensive at scale. A custom API costs a fraction and gives you full control over data.