Facebook Pixel

Socket.io Namespaces and Rooms Organizing Connections in Node.js

Learn how to use Socket.io namespaces and rooms to organize connections separating features like chat, notifications, and admin into different channels.

Socket.io Namespaces and Rooms

Namespaces and rooms are two levels of organizing Socket.io connections. Namespaces separate features, rooms group users within a namespace.

Namespaces vs Rooms

Socket.io Server
├── / (default namespace)
│   ├── Room: chat-user1-user2
│   ├── Room: chat-user3-user4
│   └── Room: notifications
├── /admin (admin namespace)
│   ├── Room: server-1
│   └── Room: server-2
└── /notifications (notifications namespace)
    └── Room: user-123

Namespace: A separate channel on the same connection. Good for separating features (chat, admin, notifications).

Room: A sub-group within a namespace. Good for grouping users (chat rooms, group chats).

Creating Namespaces

// Default namespace (/) const chatNsp = io.of("/"); // or just io // Admin namespace const adminNsp = io.of("/admin"); // Notifications namespace const notifNsp = io.of("/notifications"); // Each namespace has its own middleware and events adminNsp.use(async (socket, next) => { // Admin-specific auth const token = socket.handshake.auth.token; const decoded = jwt.verify(token, process.env.JWT_SECRET); const user = await User.findById(decoded._id); if (user.role !== "admin") { return next(new Error("Admin access required")); } socket.user = user; next(); }); adminNsp.on("connection", (socket) => { console.log("Admin connected:", socket.user.firstName); // Admin-specific events });

Client Connecting to Namespaces

// Connect to default namespace const chatSocket = io("https://api.yourdomain.com/", { auth: { token } }); // Connect to admin namespace const adminSocket = io("https://api.yourdomain.com/admin", { auth: { token } }); // Connect to notifications namespace const notifSocket = io("https://api.yourdomain.com/notifications", { auth: { token } });

Use Cases for Namespaces

  1. Chat (/) User-to-user and group chat
  2. Admin (/admin) Admin dashboard with admin-only auth
  3. Notifications (/notifications) Push notifications to users
  4. Live updates (/live) Real-time data feeds (stock prices, scores)

Broadcasting Within Namespaces

// Broadcast to all in default namespace io.emit("message", "Hello everyone"); // Broadcast to a room in default namespace io.to("room-1").emit("message", "Hello room-1"); // Broadcast to all in admin namespace io.of("/admin").emit("alert", "New admin alert"); // Broadcast to a room in admin namespace io.of("/admin").to("server-1").emit("alert", "Server 1 alert");

Notification Namespace Example

const notifNsp = io.of("/notifications"); notifNsp.use(async (socket, next) => { // Standard JWT auth const token = socket.handshake.auth.token; const decoded = jwt.verify(token, process.env.JWT_SECRET); socket.user = await User.findById(decoded._id); socket.userId = socket.user._id.toString(); next(); }); notifNsp.on("connection", (socket) => { // Join personal notification room socket.join(`user:${socket.userId}`); }); // Send notification to a specific user (from a route handler) const sendNotification = (userId, notification) => { io.of("/notifications").to(`user:${userId}`).emit("notification", notification); }; // Usage in a route router.post("/request/send/:status/:toUserId", userAuth, asyncHandler(async (req, res) => { // ... create connection request ... // Send real-time notification sendNotification(toUserId, { type: "connection_request", fromUserId: req.user._id, fromUserName: req.user.firstName, message: `${req.user.firstName} wants to connect!` }); res.status(201).json({ message: "Request sent" }); }));

The Takeaway

Socket.io namespaces separate features on the same server (chat, admin, notifications), each with its own middleware and event handlers. Rooms group users within a namespace (chat rooms, personal notification channels). Use namespaces for feature separation and authorization levels, rooms for grouping users. Broadcast with io.of('/namespace').to('room').emit().

Namespaces are top-level channels that separate features (chat, admin, notifications), each with its own auth and events. Rooms are sub-groups within a namespace for grouping users (chat rooms, group chats). Use namespaces for feature separation, rooms for user grouping.

Use io.of('/namespace-name'): const adminNsp = io.of('/admin'). Add namespace-specific middleware with adminNsp.use() and handle events with adminNsp.on('connection', ...). The client connects to the namespace with io('url/admin', { auth: { token } }).

Use namespaces to separate features with different auth requirements or event sets: chat (default /), admin dashboard (/admin with admin-only auth), notifications (/notifications for push notifications), live updates (/live for data feeds). Each namespace has its own middleware and event handlers.

When the user connects, join them to a personal room: socket.join('user:' + userId). To send a notification from a route handler: io.of('/notifications').to('user:' + userId).emit('notification', data). Only that user receives the notification.

Use io.of('/namespace').emit() for all sockets in the namespace, io.of('/namespace').to('room').emit() for a specific room, or io.of('/namespace').except('room').emit() to exclude a room. Each namespace's broadcasts only affect sockets in that namespace.

Ready to master Node.js completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.