Discover how a simple interface can save your app from security mistakes and messy code!
Why Guard interface (canActivate) in NestJS? - Purpose & Use Cases
Imagine building a web app where you must check user permissions manually on every route before showing content.
You write repeated code in each route handler to verify if the user is allowed to proceed.
This manual checking is tiring and error-prone.
You might forget to add checks on some routes, causing security holes.
It also clutters your route code, making it hard to read and maintain.
The Guard interface with canActivate lets you centralize permission checks.
You write the logic once in a guard, then apply it easily to any route.
This keeps your code clean, secure, and easy to manage.
if (!user.isAdmin) { return 'Access denied'; } // repeated in every route
canActivate(context) { const user = context.switchToHttp().getRequest().user; return user.isAdmin; } // centralized guard logicYou can protect routes consistently and cleanly, improving security and developer productivity.
In an admin dashboard, only users with admin rights can access sensitive pages. Guards ensure unauthorized users are blocked automatically.
Manual permission checks are repetitive and risky.
Guards with canActivate centralize access control.
This leads to safer, cleaner, and easier-to-maintain code.
Practice
canActivate method in a NestJS guard?Solution
Step 1: Understand the role of guards in NestJS
Guards are used to control access to routes by allowing or denying requests.Step 2: Identify the function of
ThecanActivatecanActivatemethod returns true or false to allow or deny access.Final Answer:
To decide if a request should be allowed or denied access -> Option CQuick Check:
Guard access control = canActivate returns true/false [OK]
- Confusing canActivate with response formatting
- Thinking canActivate handles database logic
- Assuming canActivate logs user actions
canActivate in NestJS?Solution
Step 1: Recognize the NestJS guard pattern
Guards are classes that implement the CanActivate interface.Step 2: Check the method signature and class syntax
The method must be named canActivate and accept an ExecutionContext parameter, returning a boolean.Final Answer:
class MyGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { return true; } } -> Option DQuick Check:
Guard class implements CanActivate with canActivate method [OK]
- Using function instead of class
- Missing implements CanActivate
- Incorrect method parameters or return type
class AlwaysDenyGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
return false;
}
}Solution
Step 1: Analyze the canActivate return value
The method always returns false, meaning access is denied.Step 2: Understand guard effect on request
When canActivate returns false, NestJS blocks the request from continuing.Final Answer:
The request is denied access -> Option AQuick Check:
canActivate false = deny request [OK]
- Assuming false allows access
- Thinking guard causes error on false
- Believing guard is skipped if false
class MyGuard implements CanActivate {
canActivate() {
return true;
}
}Solution
Step 1: Check method signature requirements
The canActivate method must accept a parameter of type ExecutionContext.Step 2: Compare with given code
The method has no parameters, which breaks the interface contract.Final Answer:
Missing parameter in canActivate method -> Option BQuick Check:
canActivate needs ExecutionContext parameter [OK]
- Omitting method parameters
- Assuming async is required
- Ignoring interface implementation rules
canActivate implementations correctly checks the role from the request object?Solution
Step 1: Access the HTTP request correctly
Usecontext.switchToHttp().getRequest()to get the request object.Step 2: Safely check the user role
Use optional chainingrequest.user?.roleto avoid errors if user is undefined.Final Answer:
canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); return request.user?.role === 'admin'; } -> Option AQuick Check:
Use switchToHttp and optional chaining for safe role check [OK]
- Using context.getUser() which does not exist
- Calling context.getRequest() directly without switchToHttp()
- Not using optional chaining causing runtime errors
Ready to prove it?
Pass the test and this pattern moves unknown
