Skip to content

Rooms and Namespaces — Complete Guide

DodaTech Updated 2026-06-28 3 min read

In this tutorial, you will learn about Rooms and Namespaces. We cover key concepts, practical examples, and best practices to help you master this topic.

Rooms and namespaces provide logical separation in Websocket applications. Namespaces split the server into independent communication channels. Rooms group connections within a namespace for targeted message delivery.

What You'll Learn

  • Socket.IO namespaces for channel separation
  • Room management: join, leave, broadcast
  • Room metadata and presence tracking
  • Namespace authentication
  • Scaling rooms across multiple servers

Why It Matters

Without rooms, every message broadcasts to all connected clients. Rooms enable targeted communication like chat rooms or document collaboration. Namespaces isolate different application domains.

Real-World Use

Discord uses rooms for voice channels. Google Docs uses rooms for document-level collaboration. Slack uses namespaces to separate workspaces and rooms for channels.

flowchart TD
    Server[Socket.IO Server] --> NS1[Namespace: /chat]
    Server --> NS2[Namespace: /admin]
    NS1 --> Room1[Room: general]
    NS1 --> Room2[Room: random]
    NS1 --> Room3[Room: tech]
    NS2 --> Room4[Room: metrics]
    Room1 --> User1[User A]
    Room1 --> User2[User B]
    Room2 --> User3[User C]

Teacher Mindset

Namespaces are like separate WebSocket servers sharing one port. Rooms are like named groups within a namespace. Use rooms for feature-level grouping (document ID, chat channel). Use namespaces for domain-level separation.

Code Examples

// Example 1: Namespace-based server
const { Server } = require('socket.io');
const io = new Server(3000);

// Main chat namespace
const chat = io.of('/chat');
chat.on('connection', (socket) => {
  console.log('Chat user:', socket.id);

  socket.on('join room', (room) => {
    socket.join(room);
    socket.to(room).emit('user joined', socket.id);
  });

  socket.on('leave room', (room) => {
    socket.leave(room);
    socket.to(room).emit('user left', socket.id);
  });

  socket.on('message', ({ room, text }) => {
    socket.to(room).emit('message', { user: socket.id, text });
  });
});

// Admin namespace with auth
const admin = io.of('/admin');
admin.use((socket, next) => {
  const token = socket.handshake.auth.token;
  if (token === 'admin-secret') {
    return next();
  }
  next(new Error('Unauthorized'));
});

admin.on('connection', (socket) => {
  socket.join('metrics');
});
// Example 2: Client joining rooms
const chat = io('/chat');

chat.on('connect', () => {
  // Join a room
  chat.emit('join room', 'general');

  // Send message to room
  chat.emit('message', { room: 'general', text: 'Hello!' });
});

chat.on('message', (msg) => {
  console.log(`${msg.user}: ${msg.text}`);
});
// Example 3: Room broadcasting patterns
const io = require('socket.io')(3000);

io.on('connection', (socket) => {
  // Join user to their personal room
  socket.join(`user:${socket.userId}`);

  // Broadcast to room excluding sender
  socket.to('room:123').emit('event', data);

  // Broadcast to room including sender
  io.to('room:123').emit('event', data);

  // Broadcast to all except sender
  socket.broadcast.emit('event', data);

  // Get room members
  const roomSize = io.sockets.adapter.rooms.get('room:123')?.size;
});

Common Mistakes

  • Broadcasting to all clients when room-specific delivery is intended
  • Forgetting to leave rooms on disconnect (Socket.IO handles this automatically)
  • Creating too many namespaces when rooms would suffice
  • Not using room-level authentication for sensitive channels
  • Assuming rooms scale across multiple servers without an Adapter

Practice

  1. Create a server with /chat and /admin namespaces.
  2. Implement room join and leave in the /chat namespace.
  3. Send room-specific messages using socket.to().
  4. Add authentication middleware to the /admin namespace.
  5. Challenge: Build a multi-room chat with room listing, member count, and room creation.

FAQ

What is the difference between a room and a namespace?

A namespace is a separate communication channel with its own middleware. A room is a subset of connections within a namespace.

How many rooms can a single socket join?

There is no hard limit. Each room join adds the socket ID to a Set in the adapter.

Do rooms work across multiple servers?

Yes, with the Redis adapter. Socket.IO uses pub/sub to synchronize rooms across server instances.

Can I send a message to a room from outside a socket handler?

Yes. Use io.to('room:123').emit() from any part of your application.

How do I check if a room exists?

Check the rooms Map in the adapter: io.sockets.adapter.rooms.get('room:123').

Mini Project

Build a multi-room chat application with Socket.IO. Implement room creation, joining, leaving, member list, and room-specific broadcasting. Add an admin namespace that broadcasts system messages to all rooms.

What's Next

Next, you will learn about broadcasting messages efficiently in WebSocket applications.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro