0
0
NestJSframework~10 mins

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

Choose your learning style9 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.