Rooms & Namespaces — Realtime

A room is a group of connections that exists only on the server. The server calls socket.join('order:12') and leave. io.to('order:12').emit(...) sends to its…

How do you make news about order #12 reach only Mr. Darto's phone, and not also the phone of Wulan, the customer who owns order #13? And how does the staff tablet come in through a guarded door? Socket.IO has two tools for that. A room is a group of connections on the server, so the server can send an event to only some of its clients. A namespace is a separate lane on one Socket.IO server, with its own entry rules, handlers and rooms.

Imagine that Mrs. Rini's Laundry has two doors: a front door for customers and a back door for staff only. Each door has its own guard. The two doors are namespaces, and their guards check who may come in. In the customers' area there is a mailbox for each order. News for order #12 goes into box #12, and only whoever holds that box's key can read it. That mailbox is a room, and the people who hold its key are the room's members. A key keeper hands out the keys, and the key keeper is the server: a customer cannot make a key of their own.

Rooms: groups of connections on the server

This is the realtime server on port 3000 (socket.io 4.8.4). The server puts a connection in an order's room when the client sends the event follow, and takes it out when the client sends unfollow:

io.on('connection', (socket) => {
  socket.on('follow', (orderId, ack) => {
    // in a real app: first check that this phone really owns that order
    socket.join(`order:${orderId}`)
    ack({ ok: true })
  })
  socket.on('unfollow', (orderId) => socket.leave(`order:${orderId}`))
})

// when Eko marks #12 as Ready for pickup:
io.to('order:12').emit('order:status', { id: 12, status: 'Ready for pickup', seq: 4 })

This is the code on Mr. Darto's phone. Each time it connects, the phone sends follow with the order number 12:

const socket = io('http://localhost:3000')

socket.on('connect', () => {
  socket.emit('follow', 12, (res) => console.log(res)) // { ok: true }
})
socket.on('order:status', (e) => show(e))

Rooms exist only on the server

Guess first: to get news about order #12 on Mr. Darto's phone, the code in its browser calls socket.join('order:12') directly. What happens?

The Socket.IO client has no join. Tried with socket.io-client 4.8.4: socket.join('order:12') in the browser throws TypeError: socket.join is not a function. A client can only ask through an event (follow), and the server decides. That is good for security: the server can check first, so Wulan cannot join the room for Mr. Darto's order.

Every socket is also put automatically in a room named after its own id. Right after connecting, socket.rooms (the list of that socket's rooms) holds one room name, the socket's own id: Set { 'VyInQSLHhBlqqnWFAAAB' }. So io.to(socket.id).emit(...) sends to that one connection.

Sending to whom

Code on the server Who receives it
io.emit(...) every socket in the default namespace /
io.to('order:12').emit(...) every member of the room, the sender included if it is a member
socket.to('order:12').emit(...) the room's members, except that socket itself
socket.broadcast.emit(...) everyone in its namespace, except that socket itself
io.to(socketId).emit(...) one connection
io.to('order:12').to('order:13').emit(...) both rooms combined; a socket in both receives it once

All of these were tried with socket.io 4.8.4.

Namespaces: a separate door for staff

Mrs. Rini and Eko use the namespace /staff. Customers stay on /. The code below creates that namespace with io.of('/staff'). It checks the staff token (a proof of who you are), then handles commands from the tablet:

const staff = io.of('/staff')

staff.use(async (socket, next) => {
  const ok = await checkStaffToken(socket.handshake.auth.token) // checked by the server
  if (!ok) return next(new Error('Not staff'))
  next()
})

staff.on('connection', (socket) => {
  socket.on('order:set-status', (d, ack) => {
    // save to the database first, then:
    io.to(`order:${d.id}`).emit('order:status', d) // customer phones, namespace /
    socket.broadcast.emit('order:status', d)        // other staff on /staff
    ack({ ok: true })
  })
})

Eko's tablet connects with io('http://localhost:3000/staff', { auth: { token } }). The server reads that auth object in socket.handshake.auth.

When a room, when a namespace

In short, a namespace separates logic at the connection level: each namespace has its own middleware and handlers. A room groups clients inside the same namespace.

Without Socket.IO: rooms with plain ws

Plain WebSocket has no rooms, so you build them yourself with a Map (tried with ws 8.22.0):

import { WebSocketServer, WebSocket } from 'ws'

const wss = new WebSocketServer({ port: 3000 })
const rooms = new Map() // 'order:12' -> Set of sockets

function join(ws, room) {
  if (!rooms.has(room)) rooms.set(room, new Set())
  rooms.get(room).add(ws)
}
function leave(ws, room) {
  const set = rooms.get(room)
  if (!set) return
  set.delete(ws)
  if (set.size === 0) rooms.delete(room) // drop an empty room
}
function toRoom(room, message, except) {
  const text = JSON.stringify(message)
  for (const ws of rooms.get(room) ?? []) {
    if (ws !== except && ws.readyState === WebSocket.OPEN) ws.send(text)
  }
}

wss.on('connection', (ws) => {
  ws.on('message', (data) => {
    const msg = JSON.parse(data)
    if (msg.type === 'join') join(ws, `order:${msg.id}`)
  })
  ws.on('close', () => {
    for (const room of [...rooms.keys()]) leave(ws, room)
  })
})

⚠️ Messages that never arrive, arrive twice, or leak to others

TL;DR: A room is a group of connections that exists only on the server. The server calls socket.join('order:12') and leave. io.to('order:12').emit(...) sends to its members. socket.to(...) and socket.broadcast skip the sender. Every socket also has a room named after its own id. A room is dropped when empty. A socket leaves all its rooms when it disconnects, so the client asks to join again in the connect handler. A namespace (io.of('/staff')) is a separate lane with its own middleware (a check before a connection is accepted), handlers and rooms, but it shares one WebSocket connection. A namespace separates logic (middleware and handlers) at the connection level; a room groups clients inside one namespace. With plain ws, a room is a Map from a name to a Set of sockets that you maintain yourself.

⚡ A room: send to some of the clients

Write:

// when Eko marks #12 as Ready for pickup:
io.to('order:12').emit('order:status', { id: 12, status: 'Ready for pickup', seq: 4 })

Meaning: A room is a group of connections on the server. io.to('order:12') sends the event to every member of the room order:12, for example Mr. Darto's phone, since he owns order #12. The phone of Wulan, who owns order #13, is in the room order:13, so it receives nothing.

⚡ Rooms exist only on the server

Guess first: on the server, socket.join puts a connection in a room. To get news about order #12, the code in the browser on Mr. Darto's phone calls socket.join('order:12') directly. What happens?

TypeError: socket.join is not a function. The client has no join. A client can only ask through an event (for example follow), and the server decides, so the server can check first.

Meaning: When a connection drops, the socket leaves all its rooms, and reconnecting creates a new socket. That is why the event follow (a request to join a room) is sent inside socket.on('connect', ...), which runs again on every reconnect.

⚡ A namespace: a separate door

Meaning: A namespace (io.of('/staff')) is a separate lane on one Socket.IO server, for example /staff for the staff tablets and / for the customers' phones. Each namespace has its own middleware (a check before a connection is accepted), handlers and rooms. In short, a namespace separates logic at the connection level, and a room groups clients inside the same namespace.

What you will learn