Bird
Raised Fist0
NestJSframework~20 mins

Rooms and namespaces in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NestJS Rooms & Namespaces Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a client joins a room in a NestJS WebSocket Gateway?

Consider a NestJS WebSocket Gateway where clients can join rooms. What is the effect of calling client.join('room1') inside a message handler?

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

@WebSocketGateway()
export class ChatGateway {
  @SubscribeMessage('joinRoom')
  handleJoinRoom(@MessageBody() room: string, @ConnectedSocket() client: Socket) {
    client.join(room);
  }
}
AThe client is removed from all other rooms automatically when joining a new room.
BThe client is disconnected from the server immediately after joining the room.
CThe client can no longer send messages to the server after joining the room.
DThe client is added to the specified room and will receive messages sent to that room.
Attempts:
2 left
💡 Hint

Think about what rooms do in socket.io and how they affect message delivery.

📝 Syntax
intermediate
2:00remaining
Which code correctly creates a namespace in a NestJS WebSocket Gateway?

In NestJS, how do you define a WebSocket Gateway that listens on a custom namespace /chat?

A
@WebSocketGateway({ path: '/chat' })
export class ChatGateway {}
B
@WebSocketGateway('/chat')
export class ChatGateway {}
C
@WebSocketGateway({ namespace: '/chat' })
export class ChatGateway {}
D
@WebSocketGateway({ url: '/chat' })
export class ChatGateway {}
Attempts:
2 left
💡 Hint

Check the official NestJS documentation for the correct option key to specify a namespace.

🔧 Debug
advanced
2:00remaining
Why does broadcasting to a room not reach clients in NestJS?

Given this code snippet, why might clients in the room not receive the broadcasted message?

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

@WebSocketGateway()
export class ChatGateway {
  @WebSocketServer()
  server: Server;

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

  handleConnection(client: Socket) {
    client.join('room1');
  }
}
AThe server property is never initialized, so broadcasting fails silently.
BClients must call join again after sending a message to receive broadcasts.
CThe room name 'room1' is invalid and must be prefixed with a slash.
DThe emit method requires a callback to confirm delivery to the room.
Attempts:
2 left
💡 Hint

Check how the server property is assigned or initialized.

❓ state_output
advanced
2:00remaining
What is the number of clients in a room after multiple joins and leaves?

Assuming clients join and leave rooms as shown, how many clients remain in room42?

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

@WebSocketGateway()
export class RoomGateway {
  @SubscribeMessage('join')
  joinRoom(@ConnectedSocket() client: Socket) {
    client.join('room42');
  }

  @SubscribeMessage('leave')
  leaveRoom(@ConnectedSocket() client: Socket) {
    client.leave('room42');
  }
}

// Scenario:
// Client A joins room42
// Client B joins room42
// Client A leaves room42
// Client C joins room42
A2
B3
C1
D0
Attempts:
2 left
💡 Hint

Count clients currently in the room after all join and leave actions.

🧠 Conceptual
expert
2:00remaining
How do namespaces and rooms differ in NestJS WebSocket gateways?

Which statement best describes the difference between namespaces and rooms in NestJS WebSocket gateways?

ANamespaces and rooms are interchangeable terms for grouping clients in NestJS gateways.
BNamespaces are separate communication channels identified by a path, while rooms are groups within a namespace for targeted messaging.
CRooms are used to authenticate clients, namespaces handle message encryption.
DRooms create new WebSocket connections, namespaces only group clients logically without new connections.
Attempts:
2 left
💡 Hint

Think about how socket.io organizes connections and message delivery.

Practice

(1/5)
1. What is the main purpose of namespaces in a NestJS WebSocket application?
easy
A. To separate communication channels for different parts of the app
B. To store user data persistently
C. To handle HTTP requests
D. To manage database connections

Solution

  1. Step 1: Understand namespaces role

    Namespaces create separate channels so different parts of the app communicate independently.
  2. Step 2: Compare other options

    Storing data, handling HTTP, or managing databases are unrelated to namespaces in WebSocket context.
  3. Final Answer:

    To separate communication channels for different parts of the app -> Option A
  4. Quick Check:

    Namespaces = separate channels [OK]
Hint: Namespaces isolate communication paths in WebSocket apps [OK]
Common Mistakes:
  • Confusing namespaces with database or HTTP handling
  • Thinking namespaces store data
  • Mixing namespaces with rooms
2. Which of the following is the correct way to create a namespace in a NestJS WebSocket gateway?
easy
A. @WebSocketGateway({ room: '/chat' })
B. @WebSocketGateway({ namespace: '/chat' })
C. @WebSocketGateway(namespace: '/chat')
D. @WebSocketGateway({ path: '/chat' })

Solution

  1. Step 1: Recall NestJS namespace syntax

    Namespaces are set using the options object with the key 'namespace'.
  2. Step 2: Check each option

    @WebSocketGateway({ namespace: '/chat' }) uses correct syntax with an options object and 'namespace' key. @WebSocketGateway({ room: '/chat' }) uses incorrect key 'room'. @WebSocketGateway(namespace: '/chat') uses wrong syntax without braces. @WebSocketGateway({ path: '/chat' }) uses 'path' which is unrelated.
  3. Final Answer:

    @WebSocketGateway({ namespace: '/chat' }) -> Option B
  4. Quick Check:

    Namespace option requires object with 'namespace' key [OK]
Hint: Use @WebSocketGateway({ namespace: '...' }) to set namespaces [OK]
Common Mistakes:
  • Using 'room' instead of 'namespace'
  • Using 'path' instead of 'namespace'
  • Omitting braces for options object
3. Given this NestJS code snippet inside a WebSocket gateway, what will be the output when a client joins the room 'room1' and the server emits to that room?
this.server.to('room1').emit('message', 'Hello Room1');
medium
A. Only clients in 'room1' receive the 'message' event with 'Hello Room1'
B. All clients connected to the namespace receive the message
C. No clients receive the message because rooms are not supported
D. Only the client who sent the message receives it

Solution

  1. Step 1: Understand room targeting

    Using to('room1') sends the event only to clients in that room.
  2. Step 2: Analyze other options

    All clients connected to the namespace receive the message is incorrect because it targets all clients, not just the room. No clients receive the message because rooms are not supported is false; rooms are supported. Only the client who sent the message receives it is wrong because emit targets room, not sender only.
  3. Final Answer:

    Only clients in 'room1' receive the 'message' event with 'Hello Room1' -> Option A
  4. Quick Check:

    Emit to room = message only to that room [OK]
Hint: Emit with .to(room) sends only to that room's clients [OK]
Common Mistakes:
  • Thinking emit sends to all clients
  • Confusing rooms with namespaces
  • Assuming sender always receives message
4. Identify the error in this NestJS WebSocket gateway code snippet:
@SubscribeMessage('joinRoom')
handleJoin(client: any, payload: { room: string }) {
  client.join(payload.room);
  client.emit('joined', `Joined room ${payload.room}`);
}
medium
A. The emit method should be called on this.server, not client
B. The event name 'joinRoom' is invalid
C. Missing namespace declaration in the gateway
D. The client object does not have a join method

Solution

  1. Step 1: Check client object methods

    The client parameter should be typed as Socket (from socket.io). Typing as any lacks type safety, intellisense, and TypeScript checks for methods like join().
  2. Step 2: Verify other options

    Event name 'joinRoom' is valid as a string. Namespace is optional. Emitting to client is valid; client.emit works.
  3. Final Answer:

    The client object does not have a join method -> Option D
  4. Quick Check:

    client must be typed as Socket with join() method [OK]
Hint: Type client as Socket to use join() safely [OK]
Common Mistakes:
  • Assuming client always has join method without typing
  • Confusing event names with invalid strings
  • Thinking emit must be on server, not client
5. You want to create a chat app with two namespaces: '/public' and '/private'. Inside '/private', users join rooms named after their user IDs. Which approach correctly sets up namespaces and rooms in NestJS?
hard
A. Use @WebSocketGateway() once and manage namespaces manually inside event handlers.
B. Create one gateway without namespaces and use client.join('/public') or client.join('/private') to simulate namespaces.
C. Create two gateways with @WebSocketGateway({ namespace: '/public' }) and @WebSocketGateway({ namespace: '/private' }). In the private gateway, use client.join(userId) to add users to their rooms.
D. Create two gateways but assign rooms globally without joining clients to rooms.

Solution

  1. Step 1: Understand namespaces and rooms setup

    Namespaces are best created as separate gateways with the namespace option. Rooms are groups inside namespaces.
  2. Step 2: Analyze options

    Create two gateways with @WebSocketGateway({ namespace: '/public' }) and @WebSocketGateway({ namespace: '/private' }). In the private gateway, use client.join(userId) to add users to their rooms. correctly creates two gateways with namespaces and uses client.join(userId) for rooms. Create one gateway without namespaces and use client.join('/public') or client.join('/private') to simulate namespaces. misuses rooms to simulate namespaces, which is incorrect. Use @WebSocketGateway() once and manage namespaces manually inside event handlers. lacks namespaces setup. Create two gateways but assign rooms globally without joining clients to rooms. creates gateways but does not join clients to rooms, so rooms won't work.
  3. Final Answer:

    Create two gateways with @WebSocketGateway({ namespace: '/public' }) and @WebSocketGateway({ namespace: '/private' }). In the private gateway, use client.join(userId) to add users to their rooms. -> Option C
  4. Quick Check:

    Namespaces = gateways; rooms = client.join() inside namespace [OK]
Hint: Use separate gateways for namespaces; join rooms inside them [OK]
Common Mistakes:
  • Using rooms to mimic namespaces
  • Not joining clients to rooms
  • Managing namespaces manually inside one gateway
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard