Bird
Raised Fist0
NestJSframework~20 mins

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

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
WebSocket Mastery in NestJS
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
How do WebSockets maintain a continuous connection?

In NestJS, WebSockets allow a server and client to communicate continuously. How does this connection stay open?

AWebSockets create a single TCP connection that stays open for ongoing two-way communication.
BThe client sends a new HTTP request for every message to keep the connection alive.
CThe server repeatedly closes and reopens connections to simulate real-time updates.
DWebSockets use multiple short-lived HTTP requests to mimic a continuous connection.
Attempts:
2 left
💡 Hint

Think about how a phone call stays open versus sending letters back and forth.

❓ component_behavior
intermediate
2:00remaining
What happens when a NestJS WebSocket Gateway receives a message?

Consider a NestJS WebSocket Gateway that listens for messages. What is the typical behavior when a message arrives?

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

@WebSocketGateway()
export class ChatGateway {
  @SubscribeMessage('message')
  handleMessage(@MessageBody() data: string): string {
    return `Received: ${data}`;
  }
}
AThe server processes the message and sends a response back to the client immediately.
BThe server queues the message but does not send any response.
CThe server ignores the message and waits for the next one.
DThe server closes the connection after receiving the message.
Attempts:
2 left
💡 Hint

Think about how a chat app replies instantly when you send a message.

❓ lifecycle
advanced
2:00remaining
What lifecycle event occurs when a client disconnects from a NestJS WebSocket Gateway?

In NestJS WebSocket Gateway, which lifecycle method is triggered when a client disconnects?

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

@WebSocketGateway()
export class ChatGateway implements OnGatewayDisconnect {
  handleDisconnect(client: any) {
    console.log('Client disconnected');
  }
}
AhandleConnection()
BhandleDisconnect()
CafterInit()
DhandleMessage()
Attempts:
2 left
💡 Hint

Think about the name that suggests a client leaving or disconnecting.

📝 Syntax
advanced
2:00remaining
Which code snippet correctly broadcasts a message to all connected clients in NestJS WebSocket Gateway?

Choose the correct way to send a message to all clients connected to a NestJS WebSocket Gateway.

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

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

  broadcastMessage(message: string) {
    // Fill in the blank
  }
}
Athis.server.sendMessage('message', message);
Bthis.server.send('message', message);
Cthis.server.emit('message', message);
Dthis.server.broadcast('message', message);
Attempts:
2 left
💡 Hint

Look for the method that sends an event to all clients in Socket.IO.

🔧 Debug
expert
3:00remaining
Why does this NestJS WebSocket Gateway fail to receive messages?

Given the following code, why does the server never log incoming messages?

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

@WebSocketGateway()
export class ChatGateway {
  @SubscribeMessage('chat')
  handleChat(@MessageBody() data: string) {
    console.log('Message:', data);
  }
}
AThe handleChat method must return a value to receive messages.
BThe @SubscribeMessage decorator is missing a required second argument.
CThe WebSocketGateway decorator requires a port number to work.
DThe client is sending messages with event name 'message' instead of 'chat'.
Attempts:
2 left
💡 Hint

Check if the event names between client and server match exactly.

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