Broadcast Messages to a Room

After users join rooms, messages can be sent only to members of a particular room.

Socket.IO provides the io.to(room).emit() method.

This sends an event to all sockets in the selected room, including the sender if the sender belongs to that room.

The socket.to(room).emit() method sends an event to other sockets in that room, excluding the current sender.

Room Broadcasting Methods

io.to(room).emit()

All room members

Includes the sender when the sender is a room member.

socket.to(room).emit()

Other room members

Excludes the current socket.

socket.rooms

Current membership

Contains the rooms joined by the current socket.

Room-Based Message Broadcasting
socket.on('room:message', (payload, acknowledge) => {
  const room = payload?.room;
  const message = payload?.message;

  if (
    typeof room !== 'string' ||
    typeof message !== 'string' ||
    message.trim().length === 0 ||
    message.length > 1000
  ) {
    acknowledge?.({
      success: false,
      error: 'Invalid message'
    });
    return;
  }

  if (!socket.rooms.has(room)) {
    acknowledge?.({
      success: false,
      error: 'Join the room before sending messages'
    });
    return;
  }

  io.to(room).emit('room:message', {
    room,
    message: message.trim(),
    timestamp: new Date().toISOString()
  });

  acknowledge?.({ success: true });
});

The server checks room membership, validates the message, broadcasts it to the room, and acknowledges the sender.

Key Takeaways
  • io.to(room).emit() targets a specific room.

  • socket.to(room).emit() excludes the current sender.

  • Validate room membership before processing room-specific events.