0
0
NestJSframework~10 mins

WebSocket guards and pipes in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - WebSocket guards and pipes
Client sends WebSocket message
WebSocket Gateway receives message
Apply Guards
Reject connection or message
Stop
Send response or event
When a WebSocket message arrives, guards check if it is allowed. If yes, pipes transform or validate the data before the handler runs.
Execution Sample
NestJS
import { WebSocketGateway, SubscribeMessage, MessageBody, UseGuards, UsePipes } from '@nestjs/websockets';
import { ValidationPipe } from '@nestjs/common';
import { IsString, IsNotEmpty } from 'class-validator';
import { WsGuard } from './ws.guard';

class MessageDto {
  @IsString()
  @IsNotEmpty()
  text: string;
}

@WebSocketGateway()
export class ChatGateway {
  @UseGuards(WsGuard)
  @SubscribeMessage('message')
  @UsePipes(new ValidationPipe())
  handleMessage(@MessageBody() data: MessageDto) {
    return { event: 'message', data };
  }
}
This code uses a guard to check access and a pipe to validate incoming WebSocket messages before handling them.
Execution Table
StepActionGuard ResultPipe ResultHandler CalledResponse Sent
1Client sends 'message' event with data {text: 'Hi'}Guard checks token: validPipe validates data: validYesSends {event: 'message', data: {text: 'Hi'}}
2Client sends 'message' event with data {text: ''}Guard checks token: validPipe validates data: invalid (empty text)NoSends error response
3Client sends 'message' event with no tokenGuard checks token: invalidPipe skippedNoSends error response
💡 Execution stops when guard denies access or pipe validation fails.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
guardResultundefinedvalidvalidinvalid
pipeResultundefinedvalidinvalidskipped
handlerCalledfalsetruefalsefalse
responsenone{event: 'message', data}error responseerror response
Key Moments - 2 Insights
Why does the handler not run when the guard fails?
Because the guard blocks unauthorized messages early, as shown in execution_table step 3 where guardResult is 'invalid' and handlerCalled is 'No'.
What happens if the pipe validation fails?
The handler is not called and an error response is sent, as in execution_table step 2 where pipeResult is 'invalid' and handlerCalled is 'No'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the guardResult at step 2?
Askipped
Bvalid
Cinvalid
Dunknown
💡 Hint
Check the 'Guard Result' column in row for step 2.
At which step does the handler get called?
AStep 1
BStep 2
CStep 3
DNone
💡 Hint
Look at the 'Handler Called' column in the execution table.
If the guard always returns valid and the pipe always passes, what changes in the execution table?
AGuard result changes to invalid
BPipe validation skipped
CHandler called in all steps
DNo response sent
💡 Hint
Refer to the 'Guard Result' and 'Handler Called' columns across steps.
Concept Snapshot
WebSocket Guards and Pipes in NestJS:
- Guards check if a message is allowed before processing.
- Pipes transform or validate message data.
- Guards run first; if they fail, processing stops.
- Pipes run next; if validation fails, handler is not called.
- Use @UseGuards() and @UsePipes() decorators on gateways or handlers.
Full Transcript
When a client sends a WebSocket message, the NestJS gateway first applies guards to check if the message is allowed. If the guard returns valid, the message data passes to pipes which validate or transform it. If the pipe validation succeeds, the message handler runs and sends a response. If either guard or pipe fails, the handler is skipped and an error response is sent. This flow ensures only authorized and valid messages are processed.