Bird
Raised Fist0
NestJSframework~10 mins

Why WebSockets enable real-time features in NestJS - Test Your Understanding

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the WebSocketGateway decorator from NestJS.

NestJS
import { [1] } from '@nestjs/websockets';
Drag options to blanks, or click blank then click option'
AWebSocketGateway
BHttpGateway
CSocketServer
DGateway
Attempts:
3 left
💡 Hint
Common Mistakes
Using HttpGateway instead of WebSocketGateway
Confusing SocketServer with the gateway decorator
2fill in blank
medium

Complete the code to create a WebSocket gateway class named 'ChatGateway'.

NestJS
@WebSocketGateway()
export class [1] {}
Drag options to blanks, or click blank then click option'
AChatGateway
BSocketGateway
CMessageGateway
DRealTimeGateway
Attempts:
3 left
💡 Hint
Common Mistakes
Using generic names like MessageGateway that don't match the example
Using names unrelated to real-time features
3fill in blank
hard

Fix the error in the method to send a message to all connected clients.

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

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

  broadcastMessage(message: string) {
    this.server.[1]('message', message);
  }
}
Drag options to blanks, or click blank then click option'
Asend
Bemit
Cbroadcast
DsendMessage
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'send' which is not a Socket.IO server method
Using 'broadcast' which is a client-side method
4fill in blank
hard

Fill in the blank to handle a client message event and respond back.

NestJS
@SubscribeMessage('[1]')
handleMessage(client: any, payload: string): string {
  return `Received: ${payload}`;
}
Drag options to blanks, or click blank then click option'
Aerror
Bconnect
Cmessage
Ddisconnect
Attempts:
3 left
💡 Hint
Common Mistakes
Using lifecycle events like connect or disconnect instead of message
Using error which is for error handling
5fill in blank
hard

Fill in the blanks to create a WebSocket gateway that logs when a client connects and disconnects.

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

@WebSocketGateway()
export class LoggerGateway implements [1], [2] {
  handleConnection(client: any) {
    console.log('Client connected:', client.id);
  }

  handleDisconnect(client: any) {
    console.log('Client disconnected:', client.id);
  }
}
Drag options to blanks, or click blank then click option'
AOnGatewayConnection
BOnGatewayDisconnect
COnGatewayInit
DOnGatewayMessage
Attempts:
3 left
💡 Hint
Common Mistakes
Using OnGatewayInit which is for initialization, not connection events
Using OnGatewayMessage which handles messages, not connections

Practice

(1/5)
1. Why do WebSockets enable real-time features in a NestJS application?
easy
A. Because they create a persistent connection allowing instant two-way communication
B. Because they use HTTP requests to fetch data periodically
C. Because they store data locally on the client device
D. Because they only send data when the user refreshes the page

Solution

  1. Step 1: Understand WebSocket connection type

    WebSockets create a persistent connection between client and server, unlike HTTP which is request-response based.
  2. Step 2: Recognize real-time communication benefit

    This persistent connection allows instant two-way communication, enabling real-time data exchange without delays.
  3. Final Answer:

    Because they create a persistent connection allowing instant two-way communication -> Option A
  4. Quick Check:

    Persistent connection = Real-time communication [OK]
Hint: Remember: WebSockets keep connection open for instant data [OK]
Common Mistakes:
  • Thinking WebSockets use periodic HTTP requests
  • Confusing local storage with real-time data transfer
  • Assuming data sends only on page refresh
2. Which of the following is the correct way to create a WebSocket gateway in NestJS?
easy
A. function createGateway() { return new WebSocket(); }
B. @WebSocketGateway() export class MyGateway {}
C. @GatewaySocket() class MyGateway {}
D. class MyGateway extends WebSocket {}

Solution

  1. Step 1: Identify NestJS WebSocket decorator

    In NestJS, the correct decorator to create a WebSocket gateway is @WebSocketGateway().
  2. Step 2: Confirm class declaration syntax

    The gateway is defined as a class exported with the decorator, matching @WebSocketGateway() export class MyGateway {}.
  3. Final Answer:

    @WebSocketGateway() export class MyGateway {} -> Option B
  4. Quick Check:

    Use @WebSocketGateway() for gateways [OK]
Hint: Look for @WebSocketGateway() decorator in NestJS [OK]
Common Mistakes:
  • Using incorrect decorator names like @GatewaySocket
  • Trying to extend WebSocket directly
  • Using plain functions instead of classes
3. Given this NestJS WebSocket gateway code snippet, what will be the output when a client sends a message 'hello'?
@WebSocketGateway()
export class ChatGateway {
  @SubscribeMessage('message')
  handleMessage(client: any, payload: string): string {
    return `Received: ${payload}`;
  }
}
medium
A. The server throws an error because of missing return type
B. The server broadcasts 'hello' to all clients
C. The server sends back 'Received: hello' to the client
D. The server ignores the message and sends nothing

Solution

  1. Step 1: Analyze the handleMessage method

    The method listens for 'message' events and returns a string with the payload included.
  2. Step 2: Understand return behavior in NestJS WebSocket

    Returning a string sends that string back only to the client who sent the message.
  3. Final Answer:

    The server sends back 'Received: hello' to the client -> Option C
  4. Quick Check:

    Return string = reply to sender [OK]
Hint: Returned string replies only to sender client [OK]
Common Mistakes:
  • Assuming message is broadcast to all clients
  • Expecting an error due to missing explicit return type
  • Thinking server ignores the message
4. Identify the error in this NestJS WebSocket gateway code:
@WebSocketGateway()
export class MyGateway {
  @SubscribeMessage('chat')
  handleChat(client, payload) {
    client.emit('chat', payload);
  }
}
medium
A. Using client.emit instead of this.server.emit for broadcasting
B. Missing type annotations for client and payload parameters
C. handleChat method should return a value to send response
D. The @SubscribeMessage decorator is misspelled

Solution

  1. Step 1: Understand client.emit vs server.emit

    Using client.emit sends message only to that client, but this.server.emit broadcasts to all connected clients.
  2. Step 2: Identify intended behavior

    Since the event is 'chat', usually the message should broadcast to all clients, so this.server.emit is correct.
  3. Final Answer:

    Using client.emit instead of this.server.emit for broadcasting -> Option A
  4. Quick Check:

    Broadcast needs this.server.emit, not client.emit [OK]
Hint: Broadcast uses this.server.emit, not client.emit [OK]
Common Mistakes:
  • Confusing client.emit with broadcast emit
  • Thinking missing types cause runtime error
  • Assuming decorator spelling is wrong
5. You want to build a live sports score update feature using NestJS WebSockets. Which approach best ensures all connected clients receive updates instantly and efficiently?
hard
A. Use client-side timers to simulate score changes without server communication
B. Send HTTP requests every 5 seconds from clients to fetch latest scores
C. Store scores in a database and let clients query on page load only
D. Use a WebSocket gateway with this.server.emit to broadcast score updates to all clients

Solution

  1. Step 1: Identify real-time update requirement

    Live sports scores need instant updates pushed to all clients without delay.
  2. Step 2: Choose efficient communication method

    Using WebSocket gateway with this.server.emit broadcasts updates instantly to all connected clients efficiently.
  3. Final Answer:

    Use a WebSocket gateway with this.server.emit to broadcast score updates to all clients -> Option D
  4. Quick Check:

    Broadcast via WebSocket = instant updates [OK]
Hint: Broadcast with this.server.emit for instant updates [OK]
Common Mistakes:
  • Using periodic HTTP polling instead of WebSockets
  • Relying on client-only timers without server data
  • Fetching data only on page load, missing live updates
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