Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: A Multi-Room Chat

Build a multi-room chat with Socket.IO: nicknames, rooms, typing indicators, history on join, acknowledgements, validation and a runnable in-memory simulation.

In this project you design and build a multi-room chat. It uses most of what you have learned: connection middleware, rooms, broadcasts that skip the sender, acknowledgements, validation, rate limiting and history for newcomers. You get the real server and client code (read-only, because Socket.IO is not installed in the runner on this site) and a runnable simulation of the same logic, so you can watch the behavior and change the rules.

Requirements

  1. Users connect with a nickname (unique, 2 to 20 characters).
  2. Users join and leave rooms. Everyone in a room sees "ana joined" and "ana left".
  3. Messages go to the room only. The sender gets confirmation through an acknowledgement.
  4. A "typing" indicator shown to the others, expiring on its own.
  5. A newcomer receives the last 20 messages of the room.
  6. A user list per room, kept up to date.
  7. Abuse protection: validate input, limit message rate.

Design

Events at a glance

Client to server join, leave, message, typing.
Server to client joined, left, message, typing, users, history.

Every client-to-server event uses an acknowledgement.

1 / 2

Three decisions are worth explaining:

  • Nickname as a handshake step. A connection middleware validates the name and rejects duplicates, so no handler ever deals with a nameless socket (security hardening).
  • Rooms as the unit of broadcast. io.to(room).emit for room messages, socket.to(room).emit to skip the sender (for "typing" and "joined").
  • History in memory. A bounded array per room. With several servers you would store messages in a database or Redis and use the offset pattern.

Server

JavaScript
// server.js
import { createServer } from "node:http";
import { Server } from "socket.io";

const httpServer = createServer();
const io = new Server(httpServer, {
  cors: { origin: process.env.CLIENT_ORIGIN ?? "http://localhost:5173" },
  maxHttpBufferSize: 1e5,
});

const history = new Map(); // room -> last 20 messages
const names = new Set();

// 1. Handshake: nickname
io.use((socket, next) => {
  const name = socket.handshake.auth?.name;
  if (typeof name !== "string" || !/^[\w -]{2,20}$/.test(name.trim())) return next(new Error("invalid name"));
  if (names.has(name.trim().toLowerCase())) return next(new Error("name taken"));
  socket.data.name = name.trim();
  names.add(name.trim().toLowerCase());
  next();
});

const usersIn = (room) => [...(io.sockets.adapter.rooms.get(room) ?? [])].map((id) => io.sockets.sockets.get(id)?.data.name);
const validRoom = (r) => typeof r === "string" && /^[a-z0-9-]{1,30}$/.test(r);

io.on("connection", (socket) => {
  const { name } = socket.data;
  const bucket = { tokens: 5, last: Date.now() };
  const allow = () => {
    const now = Date.now();
    bucket.tokens = Math.min(5, bucket.tokens + ((now - bucket.last) / 1000) * 1);
    bucket.last = now;
    return bucket.tokens-- >= 1;
  };
  const reply = (ack, body) => typeof ack === "function" && ack(body);

  socket.on("join", (room, ack) => {
    if (!validRoom(room)) return reply(ack, { ok: false, error: "invalid room" });
    socket.join(room);
    socket.to(room).emit("joined", { room, name });
    io.to(room).emit("users", { room, users: usersIn(room) });
    reply(ack, { ok: true, history: history.get(room) ?? [] });
  });

  socket.on("leave", (room, ack) => {
    if (!socket.rooms.has(room)) return reply(ack, { ok: false, error: "not in room" });
    socket.leave(room);
    socket.to(room).emit("left", { room, name });
    io.to(room).emit("users", { room, users: usersIn(room) });
    reply(ack, { ok: true });
  });

  socket.on("message", (payload, ack) => {
    if (!allow()) return reply(ack, { ok: false, error: "slow down" });
    const { room, text } = payload ?? {};
    if (!socket.rooms.has(room)) return reply(ack, { ok: false, error: "join the room first" });
    if (typeof text !== "string" || !text.trim() || text.length > 500) return reply(ack, { ok: false, error: "invalid text" });
    const msg = { id: crypto.randomUUID(), room, from: name, text: text.trim(), at: Date.now() };
    const list = history.get(room) ?? [];
    list.push(msg);
    history.set(room, list.slice(-20));
    io.to(room).emit("message", msg);   // includes the sender: one code path for rendering
    reply(ack, { ok: true, id: msg.id });
  });

  socket.on("typing", (room) => {
    if (socket.rooms.has(room)) socket.volatile.to(room).emit("typing", { room, name });
  });

  socket.on("disconnecting", () => {
    for (const room of socket.rooms) {
      if (room !== socket.id) socket.to(room).emit("left", { room, name });
    }
  });
  socket.on("disconnect", () => {
    names.delete(name.toLowerCase());
    for (const room of socket.rooms) io.to(room).emit("users", { room, users: usersIn(room) });
  });
});

httpServer.listen(3000);

Details worth noticing:

  • disconnecting fires while the socket is still in its rooms, which is the moment to tell them it left. At disconnect, socket.rooms is already empty.
  • Typing uses socket.volatile: if a "typing" event is lost, nothing matters.
  • The sender receives its own message through the room broadcast, so the UI renders messages from one place only. The ack carries just the id, to mark the pending message as sent.
  • usersIn reads the adapter's room map. With an adapter on several servers, use await io.in(room).fetchSockets() instead.

Client

JavaScript
// client.js (bundler or <script type="module">)
import { io } from "socket.io-client";

const name = prompt("Nickname?");
const socket = io("http://localhost:3000", { auth: { name } });
const currentRooms = new Set();

socket.on("connect_error", (err) => alert(`Cannot connect: ${err.message}`));

socket.on("connect", () => {
  // after a reconnect we are in no rooms: join them again
  for (const room of currentRooms) joinRoom(room);
});

function joinRoom(room) {
  socket.timeout(5000).emit("join", room, (err, res) => {
    if (err || !res.ok) return showError(err ? "timeout" : res.error);
    currentRooms.add(room);
    res.history.forEach(renderMessage);
  });
}

function send(room, text) {
  socket.timeout(5000).emit("message", { room, text }, (err, res) => {
    if (err || !res.ok) markFailed(text, err ? "timeout" : res.error);
  });
}

socket.on("message", renderMessage);
socket.on("users", ({ room, users }) => renderUsers(room, users));

let typingTimer;
input.addEventListener("input", () => {
  socket.emit("typing", activeRoom);
});
socket.on("typing", ({ name }) => {
  showTyping(`${name} is typing...`);
  clearTimeout(typingTimer);
  typingTimer = setTimeout(() => showTyping(""), 2000);   // the indicator expires by itself
});

function renderMessage(m) {
  const li = document.createElement("li");
  li.textContent = `${m.from}: ${m.text}`;   // textContent: never innerHTML
  list.append(li);
}

The connect handler re-joins rooms after a reconnection, since the new connection starts in no rooms (unless state recovery restored them).

Run the logic: an in-memory simulation

The stand-in below reproduces the server rules (nickname checks, rooms, history, rate limit, typing) with a tiny fake io. No network: it shows the behavior, and you can edit the script to change the rules.

Node.js Chat server rules in memory (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output top to bottom: the duplicate and bad names are rejected at the handshake; the history sent to ben when he joins contains ana's first message; his messages reach both of them; the "typing" event reaches ana only (it skips the sender); the empty text and unknown room come back as acknowledgement errors; and the bucket of 3 stops the flood. When ben disconnects, ana sees left.

Extensions

Try these on your own, in this order:

  1. Private messages. Join every socket to a room named user:<name> and add a dm event that emits to that room.
  2. Persistent history. Replace the in-memory map with a database and load history with WHERE id > offset.
  3. Several servers. Add the Redis adapter, replace usersIn with fetchSockets, and run two instances.
  4. Typing timeout on the server. Track the last typing time per user and send stop-typing.
  5. Reconnect handling. Turn on connection state recovery and test by cutting the network.
  6. Moderation. An admin role in socket.data allowing kick through io.in(...).disconnectSockets().

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which event should you use to notify rooms that a user is leaving the connection, and why?

    At disconnect the socket is already out of its rooms. disconnecting fires before, so you can still read socket.rooms.
  2. 2. What is the difference between io.to(room).emit and socket.to(room).emit?

    Broadcasting from a socket excludes that socket, which suits typing and join notices.
  3. 3. Why must the client rejoin its rooms after a reconnect?

    Rooms belong to the socket. A fresh connection must join again, or be restored by connection state recovery.
  4. 4. Why validate the room name and text on the server?

    Any client can send anything, so the server must check shape, length and permissions.

Summary

  • Handshake middleware sets the identity; every handler can rely on socket.data.name.
  • Rooms plus io.to and socket.to give you broadcasts with or without the sender.
  • Acknowledgements return per-call results and errors; history is sent in the join ack.
  • Use disconnecting for farewell broadcasts, volatile for typing, and validate and rate-limit everything.
  • Persistence and several servers need a database and an adapter.

Next: Project: A Live Dashboard