0
0
NestJSframework~5 mins

Protected routes with guards in NestJS - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of a guard in NestJS?
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()
What does the canActivate() method in a guard return to allow access?
Anull
Bfalse
Ctrue
Dundefined
Where do you get the HTTP request object inside a guard?
Acontext.getRequest()
Bcontext.switchToHttp().getRequest()
Ccontext.request
Dcontext.httpRequest()
What HTTP status code is returned if a guard denies access?
A403 Forbidden
B401 Unauthorized
C404 Not Found
D500 Internal Server Error
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
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.