0
0
NestJSframework~5 mins

Rooms and namespaces in NestJS

Choose your learning style9 modes available
Introduction

Rooms and namespaces help organize and control groups of users in real-time apps. They let you send messages to specific groups easily.

You want to create chat groups where only members see messages.
You need to separate users by topics or interests in a live app.
You want to limit events to certain users without broadcasting to everyone.
You want to manage different parts of your app with separate communication channels.
Syntax
NestJS
import { WebSocketGateway, SubscribeMessage, MessageBody, ConnectedSocket } from '@nestjs/websockets';
import { Socket, Server } from 'socket.io';

@WebSocketGateway({ namespace: '/chat' })
export class ChatGateway {
  server: Server;

  handleConnection(client: Socket) {
    client.join('room1');
  }

  @SubscribeMessage('message')
  handleMessage(@MessageBody() data: string, @ConnectedSocket() client: Socket) {
    this.server.to('room1').emit('message', data);
  }
}

Namespaces are set in the gateway decorator to separate communication channels.

Rooms are groups clients join to receive specific messages.

Examples
This creates a namespace called '/chat' for related events.
NestJS
@WebSocketGateway({ namespace: '/chat' })
export class ChatGateway {}
Adds the connected client to a room named 'room1'.
NestJS
client.join('room1');
Sends a message only to clients in 'room1'.
NestJS
this.server.to('room1').emit('message', data);
Sample Program

This gateway creates a '/chat' namespace. When a client connects, it joins 'room1'. Messages sent by any client are broadcast only to 'room1' members.

NestJS
import { WebSocketGateway, SubscribeMessage, MessageBody, ConnectedSocket, OnGatewayConnection } from '@nestjs/websockets';
import { Socket, Server } from 'socket.io';

@WebSocketGateway({ namespace: '/chat' })
export class ChatGateway implements OnGatewayConnection {
  server: Server;

  handleConnection(client: Socket) {
    console.log(`Client connected: ${client.id}`);
    client.join('room1');
  }

  @SubscribeMessage('message')
  handleMessage(@MessageBody() data: string, @ConnectedSocket() client: Socket) {
    console.log(`Message from ${client.id}: ${data}`);
    this.server.to('room1').emit('message', data);
  }
}
OutputSuccess
Important Notes

Rooms are temporary and tied to client connections.

Namespaces help keep different parts of your app separate.

Use console logs or browser DevTools to see connection and message flow.

Summary

Namespaces separate communication channels in your app.

Rooms group clients to target messages easily.

Use them together to organize real-time events clearly.