Building Real-Time Chat with Socket.io and MongoDB

Building Real-Time Chat with Socket.io and MongoDB

Rooms, presence, message persistence and reconnect handling for a creator collaboration platform.

Tangle Social connects content creators, and chat is where collaborations actually happen. Real-time messaging looks simple in a demo and gets interesting in production. These are the patterns that held up.

One room per conversation

Each conversation has an id, and each socket joins the rooms for the conversations its user belongs to. Emitting to a room means you never loop over users yourself.

io.on("connection", async (socket) => {
  const userId = socket.data.userId;
  const convos = await Conversation.find({ members: userId }, { _id: 1 });
  convos.forEach((c) => socket.join(String(c._id)));

  socket.on("message:send", async ({ conversationId, text }) => {
    const msg = await Message.create({ conversationId, sender: userId, text });
    io.to(conversationId).emit("message:new", msg);
  });
});

Persist first, then broadcast

Write the message to MongoDB before emitting it. If the server crashes between the two, the message still exists and clients will load it on reconnect. Broadcasting first risks messages that vanish.

Schema that scales

  • Store messages in their own collection, not embedded in the conversation document.
  • Index { conversationId: 1, createdAt: -1 } for fast paginated history.
  • Keep a lastMessage snapshot on the conversation for inbox lists.

Presence and reconnects

Track online users with a simple map from userId to socket count, so multiple tabs work. On reconnect, the client sends the id of the last message it saw and the server returns anything newer. That one step removes most "missing message" bugs.

Authentication

Verify the JWT in the Socket.io middleware, not in each event handler. Reject the connection early and store the user id on socket.data for every later event.

More on this topic

Photography
3D Models
Development
Illustrations
Fashion
Digital Art
Packaging
Motion
Illustrations
Video Production
Photography
3D Models
Development
Illustrations
Fashion