Rooms and Namespaces — Complete Guide
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
- Create a server with /chat and /admin namespaces.
- Implement room join and leave in the /chat namespace.
- Send room-specific messages using socket.to().
- Add authentication middleware to the /admin namespace.
- Challenge: Build a multi-room chat with room listing, member count, and room creation.
FAQ
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