Join a Room
Socket.IO provides socket.join(roomName) to add a socket to a room.
The method returns a Promise, so it can be awaited.
For our chat application, users will join a room by emitting the room:join event.
We will validate the room name before joining it.
Room Authorization
Validating a room name does not prove that the user has permission to access it. In production, verify membership and authorization before joining private rooms.
Join Room Event
socket.on('room:join', async (payload, acknowledge) => {
const room = payload?.room;
if (typeof room !== 'string' || !/^[a-zA-Z0-9_-]{1,50}$/.test(room)) {
acknowledge?.({
success: false,
error: 'Invalid room name'
});
return;
}
await socket.join(room);
acknowledge?.({
success: true,
room
});
});The server validates the room identifier, joins the room, and acknowledges the result.
Key Takeaways
socket.join() adds a connection to a room.
Room joining can be awaited.
Private rooms require server-side authorization.