Discover how to keep your WebSocket code clean and secure without repeating yourself!
Why WebSocket guards and pipes in NestJS? - Purpose & Use Cases
Imagine building a chat app where every message must be checked for user permission and cleaned before sending. You try to add these checks inside every message handler manually.
Manually adding checks and data cleaning in every handler is tiring, easy to forget, and leads to messy code. It's hard to keep track of who can do what and to ensure data is always safe.
WebSocket guards and pipes in NestJS let you separate permission checks and data transformations from your main code. Guards block unauthorized users early, and pipes clean or validate data automatically before your handlers run.
if (!user.isAuthorized()) { return; } const cleanData = clean(input); handleMessage(cleanData);
@UseGuards(AuthGuard)
@UsePipes(CleanPipe)
handleMessage(data) { ... }This makes your WebSocket code cleaner, safer, and easier to maintain by handling security and data processing in one place.
In a live game app, guards ensure only logged-in players can send moves, and pipes validate move data so the game logic never breaks.
Manual checks clutter your WebSocket handlers and cause bugs.
Guards block unauthorized access before your code runs.
Pipes clean and validate data automatically.
Practice
Solution
Step 1: Understand the role of guards
Guards in NestJS are used to control access by allowing or denying client connections or message handling.Step 2: Differentiate guards from pipes
Pipes transform or validate data, not control access, so they do not decide connection permissions.Final Answer:
To control access and decide if a client can connect or send messages -> Option AQuick Check:
Guards control access = A [OK]
- Confusing guards with pipes
- Thinking guards transform data
- Assuming guards handle logging
Solution
Step 1: Recall decorator usage for guards
Guards are applied using @UseGuards decorator either on the class or method. Applying on method is valid and common.Step 2: Identify correct decorator and target
@UseGuards is correct for guards; @UsePipes is for pipes, and @UseFilters is for exception filters.Final Answer:
@UseGuards(MyGuard) on the gateway method -> Option BQuick Check:
@UseGuards on method = A [OK]
- Using @UsePipes instead of @UseGuards for guards
- Applying filters instead of guards
- Applying decorators on wrong targets
@SubscribeMessage('msg')
@UsePipes(new ValidationPipe())
handleMessage(@MessageBody() data: CreateDto) {
return 'Received';
}Solution
Step 1: Understand ValidationPipe behavior
ValidationPipe checks incoming data and rejects it if invalid, sending an error response.Step 2: Analyze the method setup
The method uses @UsePipes with ValidationPipe, so invalid data triggers rejection, not acceptance or crash.Final Answer:
The message is rejected and an error is sent back to the client -> Option CQuick Check:
ValidationPipe rejects invalid data = C [OK]
- Assuming invalid data is accepted
- Thinking server crashes on invalid data
- Confusing transformation with acceptance
@SubscribeMessage('chat')
@UseGuards(AuthGuard)
@UsePipes(new ParseIntPipe())
handleChat(@MessageBody() data: string) {
return data;
}Solution
Step 1: Check pipe compatibility with data type
ParseIntPipe expects a value that can be parsed to integer, but data is a string that may not convert properly.Step 2: Validate other decorator usage
AuthGuard is valid for WebSocket guards, and decorator order does not cause error here. Returning Promise is optional.Final Answer:
ParseIntPipe cannot parse a string directly without conversion -> Option DQuick Check:
ParseIntPipe needs numeric input = D [OK]
- Assuming guards can't be used on WebSocket
- Thinking decorator order always matters
- Believing return type must be Promise
Solution
Step 1: Assign correct roles to guard and pipe
Guards handle authentication and authorization, so AuthGuard should be used as a guard.Step 2: Use ValidationPipe with DTO for payload validation
ValidationPipe validates and transforms incoming data using a DTO that checks the 'text' property.Step 3: Evaluate other options
Swapping guards and pipes misuses decorators; using guards only requires manual payload validation lacking automation; using pipes only misses authentication checks.Final Answer:
Use @UseGuards(AuthGuard) to check authentication and @UsePipes(ValidationPipe) with a DTO validating 'text' property -> Option AQuick Check:
Guard for auth + Pipe for validation = B [OK]
- Swapping guards and pipes roles
- Skipping automatic validation
- Assuming pipes handle authentication
Ready to prove it?
Pass the test and this pattern moves unknown
