Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 36 ยท Rooms and Namespaces

Room Patterns: Chat, Presence and Lobbies

Apply Socket.IO rooms to real designs. Build per-user rooms for multi-device notifications, per-resource rooms, member counts, and a capacity-limited game lobby with a start event.

You know the room API. The next skill is choosing what a room should represent. Almost every real-time feature maps onto one of a few patterns, and recognizing them lets you design events quickly and keep the code tidy. This lesson walks through four patterns with runnable examples.

Pattern 1: one room per user

A user may be logged in on a phone, a laptop and two browser tabs, each with its own socket. If the server wants to notify the user, not a specific socket, it needs a way to reach all of them. The answer: when a socket authenticates, make it join a room named after the user (for example user:42). Then io.to('user:42').emit('notification', ...) reaches every device at once.

This pattern also replaces the temptation to keep a Map<userId, socketId>, which breaks with multiple tabs and with multiple server processes.

Node.js Notify every device of one user

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.

Both of Ana's devices receive her notification; Ben's device is untouched. Because the room is keyed by a user id from authentication (not a client-supplied value), nobody can subscribe to someone else's notifications by guessing a name.

Pattern 2: one room per resource

When many users watch the same thing (a document, a project board, an order, a stock symbol), give each thing a room: doc:17, board:5, order:9021. Clients join the room when they open the resource and leave when they close it. A change to the resource is emitted to its room only.

JavaScript
socket.on('doc:open', async (docId) => {
  if (!(await canRead(socket.data.userId, docId))) return; // authorization!
  socket.join(`doc:${docId}`);
  socket.emit('doc:state', await loadDoc(docId));
});

socket.on('doc:close', (docId) => socket.leave(`doc:${docId}`));

socket.on('doc:edit', async (docId, change) => {
  if (!socket.rooms.has(`doc:${docId}`)) return; // must have joined first
  await saveChange(docId, change);
  socket.to(`doc:${docId}`).emit('doc:change', change);
});

Notice two safety checks: joining requires permission, and sending requires membership (socket.rooms.has(...)), so a client cannot write to a document it never opened.

Pattern 3: presence and counts

Showing "5 people viewing" needs the number of sockets in a room. With the default adapter it is io.sockets.adapter.rooms.get(room)?.size, and in a clustered setup (await io.in(room).fetchSockets()).length. Announce changes when someone joins or leaves, using disconnecting for the leave case because the rooms are still available there:

Node.js Viewer counts per room

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.

In the stand-in, the member set of a room is read with a helper called members(). In the real library you read io.sockets.adapter.rooms.get(room) for the same information, or use fetchSockets() when you run several servers.

Pattern 4: lobbies and matches

Games and quizzes follow a lifecycle: players join a lobby, the lobby fills up, the server starts a match and moves the players into a match room. The capacity check must be done by the server, and "full" must be reported to the player.

Node.js A lobby that starts when it is full

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.

When Ben arrives the lobby reaches capacity, so both players are moved into match:1 and receive match:start. Cleo finds an empty lobby again and simply waits (she gets an update, but nobody else is there yet).

Choosing names for rooms

Use a prefix to namespace the kinds of rooms: user:42, doc:17, match:3. Prefixes prevent collisions (a user whose id equals a document id) and make logs readable. Never let raw client text become a room name without a check; at minimum verify the format (for example with a regular expression such as /^doc:\d+$/) and then check permissions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a room named user:<id> better than a Map from userId to socketId?

    A user can have several sockets. A user room addresses all of them, and adapters share room membership between processes.
  2. 2. Where should you read socket.rooms to tell remaining members a user is leaving?

    At disconnecting the rooms are still known; at disconnect they are already empty.
  3. 3. A client emits doc:edit for a document it never opened. What check protects the data?

    Membership in the room proves the client passed the join check earlier, so the server refuses writes from non-members.
  4. 4. Why use prefixes like doc: and match: in room names?

    Prefixes separate kinds of rooms, so ids of different things cannot collide.

Summary

  • Map real concepts to rooms: user:<id> for devices of a person, <resource>:<id> for things many people watch, lobby and match rooms for games.
  • Always authorize joins and check membership before accepting writes.
  • Use disconnecting to update counts for the rooms a leaving socket was in.
  • Move players between rooms with leave and join; let the server enforce capacity.
  • Give rooms prefixed names and validate any name that comes from the client.

Next: Namespaces