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))
socket.join(name)andsocket.leave(name)put one connection in a room and take it out. A room is created when its first member joins, and is dropped automatically once it is empty (tried).io.to('order:12').emit(...)sends to every member of that room. Wulan's phone is in the roomorder:13, so it receives nothing.- When a connection drops, the socket leaves all its rooms. Reconnecting creates a new socket with a new id, which is in no room yet. That is why
followis sent insidesocket.on('connect', ...): that handler runs again on every reconnect. - Another option: the server keeps the socket's state for a short time, with
new Server(httpServer, { connectionStateRecovery: { maxDisconnectionDuration: 2 * 60 * 1000 } })(2 * 60 * 1000 milliseconds = 2 minutes). If the drop lasts less than 2 minutes, the server gives back the old id, rooms andsocket.data(data the server keeps on that socket), then sends the events that were missed. Tested with socket.io 4.8.4: after reconnecting, the id was the same, the socket was already inorder:12, and theseq: 5event sent during the drop still arrived. In the browser,socket.recoveredistrue. This recovery does not always work. Some examples: after a server restart, after a drop that lasts too long, or when the server is several processes joined through plain Redis Pub/Sub (covered in the Pub/Sub with Redis lesson). So still sendfollowinconnect, but only whensocket.recoveredisfalse.
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.
- A namespace is a path in the URL (
/staff). The default namespace is called/. - Its handlers, middleware (
use) and rooms are separate. Middleware here is a function that runs before a connection is accepted, like the door guard in the picture. The roomorder:12on/and the roomorder:12on/staffare two different rooms.io.emitonly reaches/. - Tried: a phone that opens
/staffwithout the right token getsconnect_errorwitherr.message"Not staff", and never gets in. - One page that opens both
/and/staffstill uses one WebSocket connection. Its packets carry the namespace as a prefix:42/staff,["order:status",{...}](tried).
When a room, when a namespace
- Rooms for groups that change while the app runs: per order, per chat, per user. Rooms are cheap: thousands of rooms are fine.
- Namespaces for a fixed split known from the start, with different entry rules or handlers: customers and staff. There are few of them.
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)
})
})
roomsmaps a room's name to aSetof connections.toRoomsends to each member. The parameterexceptworks likesocket.to: that connection does not receive the message.- The
closehandler is required. Without it, dead sockets stay stored inrooms, and their memory is never freed. - Namespaces with plain ws: use a different URL path (
ws://localhost:3000/staff), with its ownMapand its own checks.
⚠️ Messages that never arrive, arrive twice, or leak to others
- Calling
joinin the browser. The client has nojoin. Send an event, and the server puts the socket in the room. - Joining only once. After a reconnect, the new socket is in no room. Send
followin theconnecthandler. io.towhen you meantsocket.to. The sender receives its own message too, so a chat message already shown on its screen appears a second time.- Trusting
authfrom the client.auth: { role: 'admin' }is just text the browser sends, and anyone can write it. Check a token in middleware.
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.