Which of the following is the correct way to apply a guard to a route in NestJS?
easy📝 Syntax Q12 of 15
NestJS - Authentication
Which of the following is the correct way to apply a guard to a route in NestJS?
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
Step-by-Step Solution
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]
Quick Trick: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
Master "Authentication" in NestJS
9 interactive learning modes - each teaches the same concept differently