📖 Scenario: You are building a simple chat server using NestJS WebSocket gateway. You want to control access and validate incoming messages.
🎯 Goal: Create a WebSocket gateway with a guard that allows only authenticated users and a pipe that validates the message format.
📋 What You'll Learn
Create a WebSocket gateway class named ChatGateway
Create a guard class named AuthGuard that implements CanActivate
Create a pipe class named MessageValidationPipe that implements PipeTransform
Apply the AuthGuard to the gateway using @UseGuards(AuthGuard)
Apply the MessageValidationPipe to the message handler method using @UsePipes(MessageValidationPipe)
The message handler method should be named handleMessage and accept a message parameter
💡 Why This Matters
🌍 Real World
WebSocket guards and pipes help secure and validate real-time communication in chat apps, games, and live updates.
💼 Career
Understanding guards and pipes in NestJS is essential for backend developers building secure and robust WebSocket APIs.
Progress0 / 4 steps
1
Create the WebSocket gateway class
Create a class named ChatGateway decorated with @WebSocketGateway(). Inside it, create a method named handleMessage that takes a parameter message of type string.
NestJS
Hint
Use @WebSocketGateway() decorator from @nestjs/websockets and define the class and method exactly as named.
2
Create the AuthGuard class
Create a class named AuthGuard that implements CanActivate interface. Implement the canActivate method that returns true.
NestJS
Hint
Import CanActivate and ExecutionContext from @nestjs/common. Implement canActivate to always return true.
3
Create the MessageValidationPipe class
Create a class named MessageValidationPipe that implements PipeTransform. Implement the transform method that takes a value parameter and returns it unchanged.
NestJS
Hint
Import PipeTransform from @nestjs/common. The transform method should return the input value unchanged.
4
Apply the guard and pipe to the gateway and handler
Add the @UseGuards(AuthGuard) decorator to the ChatGateway class. Add the @UsePipes(MessageValidationPipe) decorator to the handleMessage method.
NestJS
Hint
Import UseGuards and UsePipes from @nestjs/common. Decorate the class and method exactly as specified.
Practice
(1/5)
1. What is the main purpose of a WebSocket guard in a NestJS application?
easy
A. To control access and decide if a client can connect or send messages
B. To transform incoming message data before it reaches the handler
C. To log all WebSocket messages for debugging
D. To automatically retry failed WebSocket connections
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 A
Quick Check:
Guards control access = A [OK]
Hint: Guards control access, pipes transform data [OK]
Common Mistakes:
Confusing guards with pipes
Thinking guards transform data
Assuming guards handle logging
2. Which of the following is the correct way to apply a guard to a WebSocket gateway method in NestJS?
easy
A. @UseGuards(MyGuard) on the gateway class
B. @UseGuards(MyGuard) on the gateway method
C. @UsePipes(MyGuard) on the gateway method
D. @UseFilters(MyGuard) on the gateway class
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 B
Quick Check:
@UseGuards on method = A [OK]
Hint: Use @UseGuards for guards, not pipes or filters [OK]
Common Mistakes:
Using @UsePipes instead of @UseGuards for guards
Applying filters instead of guards
Applying decorators on wrong targets
3. Given this WebSocket gateway method with a pipe, what will happen if the incoming message payload is invalid?
B. AuthGuard cannot be used with WebSocket gateways
C. @UsePipes must be placed before @UseGuards
D. ParseIntPipe cannot parse a string directly without conversion
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 D
Quick Check:
ParseIntPipe needs numeric input = D [OK]
Hint: Pipes must match expected input types [OK]
Common Mistakes:
Assuming guards can't be used on WebSocket
Thinking decorator order always matters
Believing return type must be Promise
5. You want to ensure only authenticated users can send messages and that the message payload is a valid JSON object with a 'text' property. Which combination of guard and pipe setup is best in a NestJS WebSocket gateway?
hard
A. Use @UseGuards(AuthGuard) to check authentication and @UsePipes(ValidationPipe) with a DTO validating 'text' property
B. Use @UsePipes(AuthGuard) to check authentication and @UseGuards(ValidationPipe) for payload validation
C. Use @UseGuards(AuthGuard) only, and validate payload manually inside the handler
D. Use @UsePipes(ValidationPipe) only, assuming it checks authentication too
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 A
Quick Check:
Guard for auth + Pipe for validation = B [OK]
Hint: Guards for auth, pipes for data validation [OK]
Common Mistakes:
Swapping guards and pipes roles
Skipping automatic validation
Assuming pipes handle authentication
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.