Bird
Raised Fist0
NestJSframework~20 mins

Gateway decorator in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Gateway Decorator 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 gateway?

Consider this NestJS WebSocket gateway code. What will be logged when a client connects?

NestJS
import { WebSocketGateway, OnGatewayConnection } from '@nestjs/websockets';

@WebSocketGateway()
export class MyGateway implements OnGatewayConnection {
  handleConnection(client: any, ...args: any[]) {
    console.log('Client connected:', client.id);
  }
}
ALogs 'Client connected:' followed by the client's id
BDoes not log anything because OnGatewayConnection is not implemented correctly
CLogs 'Client connected:' but client.id is undefined
DThrows a runtime error because handleConnection is missing a return type
Attempts:
2 left
💡 Hint

Check how the handleConnection method works in a gateway implementing OnGatewayConnection.

📝 Syntax
intermediate
2:00remaining
Which option correctly applies the Gateway decorator with a namespace?

Choose the correct way to define a WebSocket gateway with the namespace '/chat'.

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

Remember the Gateway decorator accepts an options object for namespace.

❓ lifecycle
advanced
2:00remaining
What happens if you implement OnGatewayDisconnect but forget to add the decorator?

Given this gateway class implementing OnGatewayDisconnect but missing the @WebSocketGateway() decorator, what is the behavior when a client disconnects?

NestJS
import { OnGatewayDisconnect } from '@nestjs/websockets';

export class MyGateway implements OnGatewayDisconnect {
  handleDisconnect(client: any) {
    console.log('Client disconnected:', client.id);
  }
}
AA runtime error occurs because the decorator is missing
BThe disconnect handler is called normally and logs the client id
CThe disconnect handler is never called because the class is not registered as a gateway
DThe server crashes on startup due to missing decorator
Attempts:
2 left
💡 Hint

Think about what the decorator does in NestJS gateways.

🔧 Debug
advanced
2:00remaining
Why does this gateway fail to emit events to clients?

Examine the code below. Why does the sendMessage method not send messages to connected clients?

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

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

  sendMessage(message: string) {
    this.server.emit('message', message);
  }
}
AThe sendMessage method is never called, so no messages are sent
BThe server property is undefined because the gateway is not instantiated by NestJS
CThe @WebSocketServer decorator is missing parentheses
DThe emit method requires a callback to confirm delivery
Attempts:
2 left
💡 Hint

Check if the method that emits messages is actually used.

🧠 Conceptual
expert
2:00remaining
What is the effect of setting 'transports' option in @WebSocketGateway decorator?

Consider this gateway decorator:

@WebSocketGateway({ transports: ['websocket'] })

What does setting transports to ['websocket'] do?

AIt causes a syntax error because transports is not a valid option
BIt enables both WebSocket and polling transports for clients
CIt disables WebSocket transport and uses only polling
DIt forces clients to connect only using WebSocket protocol, disabling polling fallback
Attempts:
2 left
💡 Hint

Think about how Socket.IO handles transports.

Practice

(1/5)
1.

What is the main purpose of the @WebSocketGateway() decorator in NestJS?

easy
A. To turn a class into a WebSocket gateway for real-time communication
B. To create a REST API controller
C. To define a database entity
D. To handle HTTP middleware

Solution

  1. Step 1: Understand the role of @WebSocketGateway()

    This decorator marks a class as a WebSocket gateway, enabling real-time communication between server and clients.
  2. Step 2: Compare with other options

    Options B, C, and D relate to REST controllers, database entities, and middleware, which are unrelated to WebSocket gateways.
  3. Final Answer:

    To turn a class into a WebSocket gateway for real-time communication -> Option A
  4. Quick Check:

    @WebSocketGateway() creates WebSocket gateways [OK]
Hint: Remember: Gateway decorator = real-time WebSocket server [OK]
Common Mistakes:
  • Confusing WebSocketGateway with REST controllers
  • Thinking it creates database entities
  • Assuming it handles HTTP middleware
2.

Which of the following is the correct syntax to create a WebSocket gateway with a custom namespace /chat?

?
easy
A. @WebSocketGateway(namespace: '/chat') export class ChatGateway {}
B. @WebSocketGateway('/chat') export class ChatGateway {}
C. @WebSocketGateway({ namespace: '/chat' }) export class ChatGateway {}
D. @WebSocketGateway({ path: '/chat' }) export class ChatGateway {}

Solution

  1. Step 1: Recall the correct options object syntax

    The @WebSocketGateway() decorator accepts an options object where namespace is a valid key to set the namespace.
  2. Step 2: Evaluate each option

    @WebSocketGateway({ namespace: '/chat' }) export class ChatGateway {} correctly uses { namespace: '/chat' }. @WebSocketGateway('/chat') export class ChatGateway {} incorrectly passes a string directly. @WebSocketGateway(namespace: '/chat') export class ChatGateway {} uses invalid syntax. @WebSocketGateway({ path: '/chat' }) export class ChatGateway {} uses path which is not the correct key for namespace.
  3. Final Answer:

    @WebSocketGateway({ namespace: '/chat' }) export class ChatGateway {} -> Option C
  4. Quick Check:

    Use options object with namespace key [OK]
Hint: Use options object with namespace key for custom namespace [OK]
Common Mistakes:
  • Passing namespace as a direct string argument
  • Using invalid syntax inside decorator
  • Confusing 'path' with 'namespace'
3.

Given the following code, what will be the output when a client connects?

@WebSocketGateway()
export class MyGateway {
  handleConnection(client: any) {
    console.log('Client connected');
  }
}
medium
A. Nothing happens because handleConnection is not called automatically
B. The server crashes due to missing WebSocket server initialization
C. An error occurs because handleConnection is missing a decorator
D. The message 'Client connected' is logged to the console when a client connects

Solution

  1. Step 1: Understand handleConnection behavior

    In NestJS WebSocket gateways, handleConnection is a lifecycle method called automatically when a client connects.
  2. Step 2: Analyze the code output

    The method logs 'Client connected' to the console, so this message appears on each client connection.
  3. Final Answer:

    The message 'Client connected' is logged to the console when a client connects -> Option D
  4. Quick Check:

    handleConnection logs message on client connect [OK]
Hint: handleConnection runs automatically on client connect [OK]
Common Mistakes:
  • Thinking handleConnection needs a decorator
  • Assuming no output without explicit event listener
  • Believing server crashes without manual init
4.

Identify the error in this WebSocket gateway code:

@WebSocketGateway()
export class AppGateway {
  @SubscribeMessage('message')
  handleMessage(client, payload) {
    client.emit('message', payload);
  }
}
medium
A. The client object does not have an emit method; it should use client.send
B. The method handleMessage should return the payload instead of emitting
C. The @SubscribeMessage decorator is missing parentheses
D. The method handleMessage must be async

Solution

  1. Step 1: Understand @SubscribeMessage handler behavior

    In NestJS, message handlers should return the response payload, not emit directly on the client.
  2. Step 2: Analyze the code's client.emit usage

    Calling client.emit is incorrect; the framework handles sending the return value automatically.
  3. Final Answer:

    The method handleMessage should return the payload instead of emitting -> Option B
  4. Quick Check:

    Return payload in handler, don't emit manually [OK]
Hint: Return data in handler; don't call client.emit manually [OK]
Common Mistakes:
  • Calling client.emit instead of returning data
  • Thinking @SubscribeMessage needs parentheses
  • Assuming handler must be async always
5.

You want to create a WebSocket gateway that listens on port 8081 and uses the namespace /notifications. Which of the following is the correct way to define this gateway?

hard
A. @WebSocketGateway({ port: 8081, namespace: '/notifications' }) export class NotificationGateway {}
B. @WebSocketGateway('/notifications', 8081) export class NotificationGateway {}
C. @WebSocketGateway({ port: 8081 }) @WebSocketGateway({ namespace: '/notifications' }) export class NotificationGateway {}
D. @WebSocketGateway(8081, { namespace: '/notifications' }) export class NotificationGateway {}

Solution

  1. Step 1: Recall the correct options object usage

    The @WebSocketGateway() decorator accepts a single options object where you can specify both port and namespace.
  2. Step 2: Evaluate each option

    @WebSocketGateway({ port: 8081, namespace: '/notifications' }) export class NotificationGateway {} correctly passes an object with both port and namespace. @WebSocketGateway(8081, { namespace: '/notifications' }) export class NotificationGateway {} incorrectly uses positional arguments mixing number and object. @WebSocketGateway({ port: 8081 }) @WebSocketGateway({ namespace: '/notifications' }) export class NotificationGateway {} uses two decorators which is invalid. @WebSocketGateway('/notifications', 8081) export class NotificationGateway {} uses positional arguments in wrong order and types.
  3. Final Answer:

    @WebSocketGateway({ port: 8081, namespace: '/notifications' }) export class NotificationGateway {} -> Option A
  4. Quick Check:

    Use single options object for port and namespace [OK]
Hint: Use one options object with port and namespace keys [OK]
Common Mistakes:
  • Passing port and namespace as separate arguments
  • Using multiple @WebSocketGateway decorators
  • Mixing argument types and order incorrectly
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