Discover how a simple guard can protect your app like a vigilant gatekeeper!
Why guards control access in NestJS - The Real Reasons
Imagine building a web app where you manually check user permissions inside every function that handles requests. You have to write the same checks over and over for each route.
Manually checking access everywhere is tiring and easy to forget. It leads to inconsistent security, bugs, and messy code that's hard to maintain.
Guards in NestJS act like gatekeepers that automatically check if a user can access a route before the request reaches your code. This keeps your app secure and your code clean.
if (user.role !== 'admin') { throw new UnauthorizedException(); } // repeated in every handler
@UseGuards(AuthGuard) // applied once to protect routes
Guards let you centralize and automate access control, making your app safer and your code easier to manage.
Think of a nightclub bouncer who checks IDs at the door so only allowed guests enter, instead of each room checking guests again.
Manual access checks are repetitive and error-prone.
Guards automate and centralize permission checks.
This improves security and keeps code clean.
Practice
Solution
Step 1: Understand the role of guards
Guards are designed to check conditions before a route handler runs, deciding if access should be granted.Step 2: Compare with other responsibilities
Formatting responses, managing database, and error handling are done by other parts of NestJS, not guards.Final Answer:
To control access by allowing or blocking requests based on conditions -> Option BQuick Check:
Guards control access = A [OK]
- Confusing guards with interceptors or filters
- Thinking guards handle data formatting
- Assuming guards manage database logic
Solution
Step 1: Recall NestJS guard syntax
Guards are applied using the @UseGuards() decorator placed before the method or class.Step 2: Evaluate options
Only @UseGuards(AuthGuard) before the method declaration uses the correct decorator syntax before the method. Others misuse syntax or placement.Final Answer:
@UseGuards(AuthGuard) before the method declaration -> Option AQuick Check:
@UseGuards decorator = A [OK]
- Using @Guard instead of @UseGuards
- Calling UseGuards as a function inside constructor
- Placing guard logic inside constructor instead of decorator
canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
return request.user && request.user.isAdmin;
}What will happen if a user without
isAdmin tries to access the guarded route?Solution
Step 1: Analyze the guard condition
The guard returns true only ifrequest.userexists andrequest.user.isAdminis truthy.Step 2: Consider user without
IfisAdminisAdminis false or missing, the condition returns false, denying access.Final Answer:
Access will be denied becauseisAdminis false or missing -> Option DQuick Check:
Guard returns false if not admin = B [OK]
- Assuming missing property causes error
- Thinking guard always returns true
- Ignoring the boolean check on isAdmin
canActivate(context: ExecutionContext) {
const request = context.getRequest();
if (!request.user) {
throw new Error('User not found');
}
return true;
}Solution
Step 1: Check method usage for request
Whilecontext.getRequest()is invalid, the main issue is guard behavior on failure.Step 2: Understand guard error handling
Guards should return false to deny access, not throw errors which cause server crashes.Final Answer:
Throwing an error inside a guard instead of returning false -> Option AQuick Check:
Guards return false, not throw errors [OK]
- Throwing errors instead of returning false
- Using incorrect context method for request
- Assuming async is required without async code
Solution
Step 1: Understand role conditions
The user must be logged in and have role 'admin' OR 'moderator' to access.Step 2: Evaluate logical operators
Return true ifrequest.userexists andrequest.user.role === 'admin' || request.user.role === 'moderator'uses OR (||) correctly. Return true ifrequest.userexists andrequest.user.role === 'admin' && request.user.role === 'moderator'uses AND (&&) which is impossible for one role. Return true ifrequest.userexists andrequest.user.role !== 'admin' || request.user.role !== 'moderator'uses negations incorrectly. Return true ifrequest.userdoes not exist allows access without user.Final Answer:
Return true ifrequest.userexists andrequest.user.role === 'admin' || request.user.role === 'moderator'-> Option CQuick Check:
Use OR for multiple allowed roles = D [OK]
- Using AND (&&) instead of OR (||) for roles
- Allowing access when user is missing
- Incorrect negation logic in conditions
Ready to prove it?
Pass the test and this pattern moves unknown
