Bird
Raised Fist0
NestJSframework~20 mins

WebSocket gateway creation in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
WebSocket Gateway Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when a client connects to this NestJS WebSocket gateway?
Consider this NestJS WebSocket gateway code. What message will the server send to the client immediately after connection?
NestJS
import { WebSocketGateway, OnGatewayConnection, WebSocketServer } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

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

  handleConnection(client: Socket) {
    client.emit('welcome', 'Hello Client!');
  }
}
AThe server throws an error because handleConnection is missing a return type.
BThe client receives no message until it sends one first.
CThe client receives a message 'welcome' but with an empty string.
DThe client receives the message 'Hello Client!' immediately after connecting.
Attempts:
2 left
💡 Hint
Look at what the handleConnection method does with the client socket.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a WebSocket gateway listening on port 3001?
You want to create a NestJS WebSocket gateway that listens on port 3001. Which code snippet correctly sets this up?
A
@WebSocketGateway({ port: 3001 })
export class MyGateway {}
B
@WebSocketGateway(3001)
export class MyGateway {}
C
@WebSocketGateway(port=3001)
export class MyGateway {}
D
@WebSocketGateway(port: 3001)
export class MyGateway {}
Attempts:
2 left
💡 Hint
Check the decorator syntax for passing options as an object.
❓ lifecycle
advanced
2:00remaining
What happens if you implement OnGatewayDisconnect but forget to handle the disconnect event?
Given this gateway code, what will be the behavior when a client disconnects?
NestJS
import { WebSocketGateway, OnGatewayDisconnect } from '@nestjs/websockets';
import { Socket } from 'socket.io';

@WebSocketGateway()
export class MyGateway implements OnGatewayDisconnect {
  handleDisconnect(client: Socket) {
    // Intentionally left blank
  }
}
AThe client connection remains open because disconnect is not handled properly.
BThe server throws a runtime error because handleDisconnect is empty.
CThe server logs nothing and silently ignores the disconnect event.
DThe server automatically reconnects the client.
Attempts:
2 left
💡 Hint
Think about what an empty method implementation means for event handling.
🔧 Debug
advanced
2:00remaining
Why does this WebSocket gateway fail to emit messages to all clients?
Review this gateway code. Why does calling this.server.emit('msg', 'hello') not send messages to all connected clients?
NestJS
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Server } from 'socket.io';

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

  sendMessage() {
    this.server.emit('msg', 'hello');
  }
}
AThe server property is undefined because @WebSocketServer decorator is missing parentheses.
BThe server property is undefined because the gateway is not instantiated by NestJS.
CThe server property is undefined because the class lacks the OnGatewayInit interface implementation.
DThe server property is undefined because the @WebSocketServer decorator is not imported from the correct package.
Attempts:
2 left
💡 Hint
Consider how NestJS creates and manages gateway instances and their properties.
🧠 Conceptual
expert
3:00remaining
How does NestJS WebSocket gateway handle multiple namespaces?
You want to create two WebSocket gateways in NestJS, each listening on a different namespace: '/chat' and '/news'. How should you configure the gateways to achieve this?
AUse @WebSocketGateway({ namespace: '/chat' }) on one class and @WebSocketGateway({ namespace: '/news' }) on the other.
BUse @WebSocketGateway('/chat') on one class and @WebSocketGateway('/news') on the other.
CUse @WebSocketGateway() on both classes and manually filter namespaces inside handleConnection.
DUse a single gateway with @WebSocketGateway() and handle namespaces via client-side events.
Attempts:
2 left
💡 Hint
Check how the namespace option is passed in the decorator options object.

Practice

(1/5)
1. What is the main purpose of a WebSocket gateway in a NestJS application?
easy
A. To serve static files like images and CSS
B. To handle real-time communication between server and clients
C. To manage database connections
D. To handle HTTP request routing

Solution

  1. Step 1: Understand WebSocket gateway role

    A WebSocket gateway is designed to manage real-time, two-way communication between the server and clients.
  2. Step 2: Compare with other server roles

    Managing database connections, serving static files, or HTTP routing are handled by other parts of NestJS, not WebSocket gateways.
  3. Final Answer:

    To handle real-time communication between server and clients -> Option B
  4. Quick Check:

    WebSocket gateway = real-time communication [OK]
Hint: WebSocket gateways are for live message exchange [OK]
Common Mistakes:
  • Confusing WebSocket gateway with HTTP routing
  • Thinking it manages database connections
  • Assuming it serves static files
2. Which decorator is used to define a WebSocket gateway class in NestJS?
easy
A. @Gateway()
B. @SocketGateway()
C. @WebSocketGateway()
D. @WebSocketServer()

Solution

  1. Step 1: Identify the correct decorator for gateway class

    The official NestJS decorator to create a WebSocket gateway class is @WebSocketGateway().
  2. Step 2: Differentiate from other decorators

    @WebSocketServer() is used inside the class to inject the server instance, not to define the class itself. The others are incorrect or do not exist.
  3. Final Answer:

    @WebSocketGateway() -> Option C
  4. Quick Check:

    Gateway class decorator = @WebSocketGateway() [OK]
Hint: Gateway class always uses @WebSocketGateway() [OK]
Common Mistakes:
  • Using @WebSocketServer() to decorate the class
  • Confusing with non-existent decorators
  • Omitting parentheses on the decorator
3. Given this NestJS WebSocket gateway code, what will be logged when a client sends a 'message' event with payload 'Hello'?
import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets';

@WebSocketGateway()
export class ChatGateway {
  @SubscribeMessage('message')
  handleMessage(@MessageBody() data: string): string {
    console.log('Received:', data);
    return `Echo: ${data}`;
  }
}
medium
A. Received: Hello
B. Echo: Hello
C. message event received
D. No output logged

Solution

  1. Step 1: Analyze the handleMessage method

    The method logs the string 'Received:' followed by the data payload, which is 'Hello'.
  2. Step 2: Understand what is returned vs logged

    The return value is 'Echo: Hello', but only the console.log outputs to the server console. The client receives the return value, but the question asks about what is logged.
  3. Final Answer:

    Received: Hello -> Option A
  4. Quick Check:

    Console logs 'Received: Hello' [OK]
Hint: Look for console.log to find logged output [OK]
Common Mistakes:
  • Confusing returned value with logged output
  • Assuming client message is logged
  • Ignoring the console.log statement
4. Identify the error in this WebSocket gateway code snippet:
import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets';

@WebSocketGateway()
export class MyGateway {
  @SubscribeMessage('chat')
  onChat(data: string) {
    return `Message: ${data}`;
  }
}
medium
A. Method onChat must be async
B. Incorrect event name in @SubscribeMessage decorator
C. WebSocketGateway decorator requires a port number
D. Missing @MessageBody() decorator on the method parameter

Solution

  1. Step 1: Check method parameter decorators

    In NestJS WebSocket gateways, to receive the message payload, the parameter must be decorated with @MessageBody().
  2. Step 2: Verify other parts

    The event name 'chat' is valid, @WebSocketGateway() can be used without a port, and the method does not need to be async unless awaiting something.
  3. Final Answer:

    Missing @MessageBody() decorator on the method parameter -> Option D
  4. Quick Check:

    Parameter needs @MessageBody() [OK]
Hint: Always decorate message parameters with @MessageBody() [OK]
Common Mistakes:
  • Omitting @MessageBody() on parameters
  • Thinking port number is mandatory
  • Assuming method must be async
5. How can you broadcast a message to all connected clients from within a NestJS WebSocket gateway?
hard
A. Use the injected server instance with this.server.emit('event', data)
B. Return the message string from the event handler method
C. Call client.send(data) on a single client only
D. Use @SubscribeMessage('broadcast') decorator on the method

Solution

  1. Step 1: Understand broadcasting in NestJS gateways

    To send a message to all clients, you use the server instance injected with @WebSocketServer() and call emit on it.
  2. Step 2: Differentiate from other options

    Returning a string sends a response only to the sender. Calling client.send() targets one client. The decorator @SubscribeMessage() only listens for events, it does not broadcast.
  3. Final Answer:

    Use the injected server instance with this.server.emit('event', data) -> Option A
  4. Quick Check:

    Broadcast = this.server.emit() [OK]
Hint: Broadcast with this.server.emit() inside gateway [OK]
Common Mistakes:
  • Returning message instead of emitting
  • Sending to one client only
  • Misusing decorators for broadcasting
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