Facebook Pixel

Socket.io Rooms and Broadcasting Group Communication in Node.js

Learn how to use Socket.io rooms for group communication in Node.js creating rooms, joining, broadcasting, and managing private conversations.

Socket.io Rooms and Broadcasting

Rooms are a core Socket.io feature for grouping connections. They enable group chat, private conversations, and targeted broadcasting.

What Are Rooms?

A room is a named channel that sockets can join and leave. When you broadcast to a room, only sockets in that room receive the message.

Socket A joins "room-1"
Socket B joins "room-1"
Socket C joins "room-2"

Broadcast to "room-1" → Only A and B receive it
Broadcast to "room-2" → Only C receives it

Joining and Leaving Rooms

io.on("connection", (socket) => { // Join a room socket.join("room-1"); // Join multiple rooms socket.join(["room-1", "room-2"]); // Leave a room socket.leave("room-1"); // Get all rooms this socket is in console.log(socket.rooms); // Set { "socket-id", "room-1" } });

Broadcasting to Rooms

// Broadcast to all sockets in a room (including sender) io.to("room-1").emit("message", "Hello everyone in room-1!"); // Broadcast to multiple rooms io.to("room-1").to("room-2").emit("announcement", "Important!"); // Broadcast to all sockets EXCEPT the sender socket.to("room-1").emit("message", "Someone joined room-1"); // Broadcast to all connected sockets io.emit("announcement", "Server maintenance in 10 minutes");

Private Chat Rooms (1-on-1)

For private chats between two users, create a unique room:

// Create a deterministic room ID for two users const getRoomId = (userId1, userId2) => { return [userId1, userId2].sort().join("_"); }; io.on("connection", (socket) => { socket.on("join:chat", ({ targetUserId }) => { const roomId = getRoomId(socket.userId, targetUserId); socket.join(roomId); socket.emit("room:joined", { roomId }); // Notify the other user socket.to(targetUserId).emit("chat:request", { fromUserId: socket.userId, roomId }); }); socket.on("message:send", ({ targetUserId, text }) => { const roomId = getRoomId(socket.userId, targetUserId); // Save to database const message = await Message.create({ senderId: socket.userId, receiverId: targetUserId, text }); // Broadcast to the room (both users) io.to(roomId).emit("message:received", { _id: message._id, senderId: socket.userId, text, createdAt: message.createdAt }); }); });

Group Chat Rooms

io.on("connection", (socket) => { // Join a group chat socket.on("group:join", ({ groupId }) => { socket.join(`group:${groupId}`); socket.to(`group:${groupId}`).emit("user:joined", { userId: socket.userId, name: socket.user.firstName }); }); // Send group message socket.on("group:message", ({ groupId, text }) => { const message = { senderId: socket.userId, groupId, text, createdAt: new Date() }; // Broadcast to all group members io.to(`group:${groupId}`).emit("group:message", message); }); // Leave group socket.on("group:leave", ({ groupId }) => { socket.leave(`group:${groupId}`); socket.to(`group:${groupId}`).emit("user:left", { userId: socket.userId }); }); });

Presence (Online/Offline Status)

const onlineUsers = new Map(); io.on("connection", (socket) => { onlineUsers.set(socket.userId, socket.id); // Broadcast online status io.emit("user:online", { userId: socket.userId }); socket.on("disconnect", () => { onlineUsers.delete(socket.userId); io.emit("user:offline", { userId: socket.userId }); }); }); // API to check if a user is online const isUserOnline = (userId) => onlineUsers.has(userId);

The Takeaway

Socket.io rooms enable group communication. Use deterministic room IDs for private chats (sort and join user IDs), join rooms with socket.join(), broadcast with io.to(roomId).emit() (includes sender) or socket.to(roomId).emit() (excludes sender), use group:groupId for group chats, and track online users with a Map for presence status. Rooms are essential for chat applications.

Rooms are named channels that sockets can join and leave. When you broadcast to a room, only sockets in that room receive the message. Use socket.join('roomName') to join, socket.leave('roomName') to leave, and io.to('roomName').emit() to broadcast to all sockets in the room.

Create a deterministic room ID by sorting and joining the two user IDs: [userId1, userId2].sort().join('_'). Both users join the same room. Broadcast messages with io.to(roomId).emit(). This ensures only the two users in the conversation receive messages.

io.to(roomId).emit() broadcasts to ALL sockets in the room, including the sender. socket.to(roomId).emit() broadcasts to all sockets in the room EXCEPT the sender. Use io.to() when the sender should also see the message, socket.to() for notifications to others.

Maintain a Map of online users (userId → socketId). On connection, add the user and broadcast 'user:online'. On disconnect, remove the user and broadcast 'user:offline'. Provide an API or Socket.io event to check if a specific user is online.

Use a room named group:groupId. Users join with socket.join('group:' + groupId). Messages are broadcast with io.to('group:' + groupId).emit('group:message', message). When a user leaves, call socket.leave() and notify the group.

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.