Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท Rooms and Namespaces

Socket.IO Rooms: Grouping Sockets

Learn Socket.IO rooms. Join and leave rooms, send to one or several rooms, exclude sockets, understand the automatic personal room, inspect room members and avoid common mistakes.

Broadcasting to everyone is rarely what you want. A chat app has many conversations; a game has many matches; a dashboard has users watching different projects. A room is a named group of sockets on the server. You put sockets into rooms, then send an event to a room, and only its members receive it. Rooms are the most useful organizational tool in Socket.IO, and they are very cheap: a room is just a name that exists while it has members.

Key facts about rooms

  • Rooms are a server-side concept. A client cannot join a room directly; it asks the server (with an event) and the server calls socket.join.
  • A room is created automatically when the first socket joins and disappears when the last one leaves. There is nothing to "create" or "delete".
  • A socket can be in many rooms at once.
  • Every socket automatically joins a room named after its own socket.id. That is why io.to(socket.id).emit(...) sends a private message to one socket.
  • Rooms belong to a namespace (next lessons); the default namespace is /.
  • On disconnect, the socket leaves all rooms automatically.

The room API

JavaScript
socket.join('lobby');                 // join one room
socket.join(['news', 'sports']);      // join several
socket.leave('lobby');                // leave

io.to('lobby').emit('hello');         // everyone in lobby
io.to('lobby').to('news').emit('x');  // union of both rooms (a socket in both gets it once)
io.in('lobby').emit('hello');         // "in" is an alias of "to"
io.except('lobby').emit('x');         // everyone NOT in lobby
io.to('lobby').except('muted').emit('x');
socket.to('lobby').emit('hi');        // lobby members EXCEPT this socket

socket.rooms;                         // Set: this socket's id and joined rooms

Two details to remember. First, socket.to('lobby').emit(...) excludes the calling socket, while io.to('lobby').emit(...) includes it if it is a member. Second, socket.join is synchronous with the default in-memory adapter but may return a promise with other adapters (for example Redis), so await socket.join(...) is the safe habit.

A first room example

Ana and Ben join the room lobby; Cleo stays outside. A message sent to the room reaches only the two members.

Node.js Joining and sending to a 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.

Cleo never hears anything, because she is in no room (apart from her private one). Ana hears her own say message but not the whisper-to-others one.

Leaving, moving and the personal room

Moving a user from one room to another is a leave plus a join. The personal room lets you address one specific socket without keeping your own map of sockets: io.to(socketId).emit('private', ...).

Node.js Switching rooms and private messages

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 Ana switches, Ben (still in room-a) is told she left, and only Ana (now alone in room-b) hears that she joined.

Inspecting rooms

On the server you can look at who is where:

JavaScript
io.sockets.adapter.rooms;            // Map: room name -> Set of socket ids
io.sockets.adapter.rooms.get('lobby')?.size; // number of members
const sockets = await io.in('lobby').fetchSockets(); // socket objects (works across servers)

adapter.rooms also contains one entry per socket id (the personal rooms), so to list only "real" rooms filter out names that are socket ids. fetchSockets() is the portable way, because it also works when you scale out with an adapter.

Common mistakes

  • Trusting the client's room name. If the client emits join with any string, users could enter rooms they should not see (for example admin or another user's user:42). Check permissions in the handler.
  • Forgetting that reconnects lose rooms. A new socket is in no rooms; re-join in the connection handler (or enable state recovery).
  • Using socket.emit when you meant the room. socket.emit is only the sender.
  • Giant room names or ids built from user input without limits; validate them.
  • Assuming order of delivery across rooms when a socket is in several of them; each event is delivered once per target set, but nothing coordinates two separate emits.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Who calls socket.join('lobby') for a client?

    Rooms live on the server. A client asks via an event and the server decides whether to add it.
  2. 2. What does socket.to('lobby').emit('x') send to?

    socket.to excludes the calling socket; io.to would include it if it is a member.
  3. 3. How can you send a private event to one socket if you know its id?

    Every socket is automatically in a room named after its id.
  4. 4. What happens to a socket's rooms when it reconnects after a drop (without state recovery)?

    The reconnected socket is brand new; re-join rooms in the connection handler.

Summary

  • A room is a server-side named group of sockets; it exists while it has members.
  • join, leave, to/in, except and socket.rooms are the core of the API.
  • Every socket is automatically in a room named after its id, enabling private messages.
  • socket.to(room) excludes the sender; io.to(room) includes members, the sender among them.
  • Validate who may join which room, and re-join after reconnects.

Next: Room Patterns: Chat, Presence and Lobbies