Bird
Raised Fist0
NestJSframework~10 mins

WebSocket gateway creation in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - WebSocket gateway creation
Start NestJS App
↓
Define Gateway Class
↓
Add @WebSocketGateway Decorator
↓
Implement Event Handlers
↓
NestJS Creates WebSocket Server
↓
Client Connects
↓
Handle Messages & Send Responses
↓
Client Disconnects
↓
End
The flow shows how NestJS creates a WebSocket gateway class, sets up event handlers, starts the server, and manages client connections and messages.
Execution Sample
NestJS
import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets';

@WebSocketGateway()
export class ChatGateway {
  @SubscribeMessage('message')
  handleMessage(@MessageBody() data: string): string {
    return `Received: ${data}`;
  }
}
This code creates a WebSocket gateway that listens for 'message' events and replies with a confirmation string.
Execution Table
StepActionInput/EventInternal StateOutput/Response
1NestJS starts and scans for gatewaysApp startGateway class registeredWebSocket server ready
2Client connectsClient connects to WS serverConnection establishedConnection acknowledged
3Client sends 'message' event'message' with data='Hello'handleMessage called with data='Hello'Returns 'Received: Hello'
4Server sends responseSend response to clientResponse sentClient receives 'Received: Hello'
5Client disconnectsClient closes connectionConnection closedCleanup done
6EndNo more eventsIdleNo output
💡 Execution stops when client disconnects and no more events occur.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
dataundefinedundefined'Hello''Hello'undefined
connectionnoneestablishedestablishedestablishedclosed
responsenonenonenone'Received: Hello'none
Key Moments - 3 Insights
Why does the handleMessage method receive the message data as a parameter?
Because the @SubscribeMessage decorator listens for the 'message' event and passes the message payload to the method as the parameter decorated with @MessageBody, as shown in step 3 of the execution_table.
What happens if the client sends a different event name?
The gateway will ignore it unless there is a method decorated with @SubscribeMessage for that event. Only events with matching handlers trigger methods, as seen in step 3 where 'message' triggers handleMessage.
How does the server send a response back to the client?
The method returns a value which NestJS sends automatically as a response to the client event, demonstrated in step 4 where the returned string is sent back.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'data' at Step 3?
Aundefined
B'Hello'
C'Received: Hello'
Dnull
💡 Hint
Check the 'Input/Event' and 'Internal State' columns at Step 3 in the execution_table.
At which step does the client disconnect from the WebSocket server?
AStep 2
BStep 3
CStep 5
DStep 6
💡 Hint
Look for the 'Client disconnects' action in the execution_table.
If the client sends an event named 'ping' instead of 'message', what happens?
ANo method is called, no response sent
BhandleMessage is called with 'ping' data
CServer crashes
DClient disconnects immediately
💡 Hint
Refer to the key_moments explanation about event names and handlers.
Concept Snapshot
NestJS WebSocket Gateway:
- Use @WebSocketGateway() on a class
- Use @SubscribeMessage('event') on methods
- Methods receive data via @MessageBody()
- Return value is sent back to client
- Handles client connect, message, disconnect
- Easy real-time communication setup
Full Transcript
This visual execution trace shows how to create a WebSocket gateway in NestJS. First, NestJS starts and registers the gateway class decorated with @WebSocketGateway. When a client connects, the server establishes a connection. When the client sends a 'message' event with data, the handleMessage method is called with that data. The method returns a string response which NestJS sends back to the client. Finally, when the client disconnects, the connection closes and the server cleans up. Variables like 'data', 'connection', and 'response' change state during these steps. Common confusions include how the message data is passed to the method, what happens with unknown events, and how responses are sent. The quizzes test understanding of these execution steps. This process enables easy real-time communication using WebSockets in NestJS.

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