A guard in NestJS controls access to routes by deciding if a request should proceed based on conditions like authentication or roles.
Click to reveal answer
beginner
How do you apply a guard to protect a route in NestJS?
You apply a guard by using the @UseGuards() decorator on a controller or route handler to check conditions before allowing access.
Click to reveal answer
intermediate
What method must a NestJS guard implement?
A NestJS guard must implement the canActivate() method, which returns true or false (or a Promise/Observable of these) to allow or deny access.
Click to reveal answer
intermediate
How can you access the current request inside a guard?
Inside canActivate(), you can access the request object via the ExecutionContext parameter using context.switchToHttp().getRequest().
Click to reveal answer
beginner
What happens if a guard returns false in canActivate()?
If canActivate() returns false, NestJS denies the request and responds with a 403 Forbidden error by default.
Click to reveal answer
Which decorator is used to apply a guard to a route in NestJS?
A@UseGuards()
B@Guard()
C@Protect()
D@Auth()
✗ Incorrect
The @UseGuards() decorator is the correct way to apply guards to routes or controllers.
What does the canActivate() method in a guard return to allow access?
Anull
Bfalse
Ctrue
Dundefined
✗ Incorrect
Returning true from canActivate() means the request is allowed to proceed.
Where do you get the HTTP request object inside a guard?
Acontext.getRequest()
Bcontext.switchToHttp().getRequest()
Ccontext.request
Dcontext.httpRequest()
✗ Incorrect
The correct way is context.switchToHttp().getRequest() to access the request in HTTP context.
What HTTP status code is returned if a guard denies access?
A403 Forbidden
B401 Unauthorized
C404 Not Found
D500 Internal Server Error
✗ Incorrect
By default, NestJS returns 403 Forbidden when a guard returns false.
Can guards in NestJS be asynchronous?
AOnly if using middleware
BNo, canActivate() must be synchronous
COnly if using callbacks
DYes, canActivate() can return a Promise or Observable
✗ Incorrect
Guards can be async by returning a Promise or Observable from canActivate().
Explain how to create and use a guard to protect a route in NestJS.
Think about how NestJS checks access before running route handlers.
You got /5 concepts.
Describe what happens when a guard denies access to a route in NestJS.
Focus on the flow after canActivate returns false.
You got /4 concepts.
Practice
(1/5)
1. What is the main purpose of a guard in NestJS when protecting routes?
easy
A. To decide if a request can access a route based on custom logic
B. To format the response data before sending it
C. To handle database connections automatically
D. To log every request made to the server
Solution
Step 1: Understand the role of guards
Guards in NestJS are designed to control access to routes by running custom logic before the route handler executes.
Step 2: Identify the correct purpose
Among the options, only deciding if a request can access a route matches the guard's role.
Final Answer:
To decide if a request can access a route based on custom logic -> Option A
Quick Check:
Guards control access = C [OK]
Hint: Guards allow or block access before route runs [OK]
Common Mistakes:
Confusing guards with interceptors or middleware
Thinking guards modify response data
Assuming guards handle database tasks
2. Which of the following is the correct way to apply a guard to a route in NestJS?
easy
A. @UseGuards(AuthGuard) before the controller class
B. @UseGuards(AuthGuard) before the route handler method
C. @ApplyGuard(AuthGuard) inside the constructor
D. @Guard(AuthGuard) before the route handler
Solution
Step 1: Recall the decorator for guards
The correct decorator to apply guards in NestJS is @UseGuards().
Step 2: Identify correct placement
This decorator can be placed before a route handler method or a controller class. @UseGuards(AuthGuard) before the route handler method correctly shows it before a route handler method.
Final Answer:
@UseGuards(AuthGuard) before the route handler method -> Option B
Quick Check:
@UseGuards + route method = D [OK]
Hint: Use @UseGuards() decorator on methods or controllers [OK]
Common Mistakes:
Using @Guard or @ApplyGuard which don't exist
Placing decorators inside constructor
Confusing middleware with guards
3. Given this guard implementation, what will happen when a request is made?
A. The guard throws an error causing a server crash
B. The route handler runs and returns its response
C. The request is blocked and the route handler does not run
D. The guard logs the request but allows it
Solution
Step 1: Analyze the canActivate method
The guard's canActivate method always returns false, meaning it denies access.
Step 2: Understand guard effect on route
When canActivate returns false, NestJS blocks the request and does not run the route handler.
Final Answer:
The request is blocked and the route handler does not run -> Option C
Quick Check:
canActivate false blocks request = A [OK]
Hint: canActivate false means block access [OK]
Common Mistakes:
Thinking false lets the route run
Assuming guard throws error on false
Confusing logging with blocking
4. Identify the error in this guard code snippet:
import { CanActivate, ExecutionContext } from '@nestjs/common';
export class MyGuard implements CanActivate {
canActivate(context: ExecutionContext) {
if (context.switchToHttp().getRequest().user) {
return true;
}
}
}
medium
A. Incorrect import of ExecutionContext
B. Using switchToHttp() is not allowed in guards
C. canActivate should be async but is not
D. Missing return statement when user is not present
Solution
Step 1: Check canActivate return paths
The method returns true if user exists, but returns nothing (undefined) otherwise.
Step 2: Understand guard return requirements
canActivate must always return a boolean or Promise<boolean>. Missing return means undefined, which is invalid.
Final Answer:
Missing return statement when user is not present -> Option D
Quick Check:
All paths must return boolean = B [OK]
Hint: Always return true or false in canActivate [OK]
Common Mistakes:
Forgetting else return false
Assuming undefined is false
Thinking async is always required
5. You want to protect a route so only users with role 'admin' can access it. Which guard implementation correctly enforces this?
import { CanActivate, ExecutionContext } from '@nestjs/common';
export class RolesGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const user = request.user;
// Which condition correctly checks for admin role?
}
}
hard
A. return user && user.role === 'admin';
B. return user && user.roles.includes('admin');
C. return user && user.roles === 'admin';
D. return user && user.role.includes('admin');
Solution
Step 1: Understand user role structure
Assuming user has a single role string in property role, not an array.
Step 2: Check each condition
return user && user.role === 'admin'; correctly compares user.role === 'admin'. return user && user.roles.includes('admin'); assumes roles is an array, which may be incorrect. Options C and D misuse property types.
Final Answer:
return user && user.role === 'admin'; -> Option A
Quick Check:
Check user.role string equals 'admin' = A [OK]
Hint: Match exact role property type to check admin [OK]
Common Mistakes:
Confusing roles array with single role string
Using includes on a string property
Checking wrong property name
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.