0
0
NestJSframework~10 mins

Guard interface (canActivate) in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Guard interface (canActivate)
Request comes in
Guard's canActivate called
Check condition inside canActivate
Allow
Route
When a request arrives, NestJS calls the guard's canActivate method. If it returns true, the request proceeds. If false, access is blocked.
Execution Sample
NestJS
import { CanActivate, ExecutionContext } from '@nestjs/common';

export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return !!request.user;
  }
}
This guard checks if the request has a user object. If yes, it allows access; otherwise, it blocks.
Execution Table
StepActionEvaluationResult
1Request arrivesN/ATrigger canActivate
2Extract request from contextrequest object obtainedrequest.user exists?
3Check if request.user is truthyrequest.user = undefinedfalse
4Return false from canActivateAccess deniedRoute handler NOT called
5Request arrivesN/ATrigger canActivate
6Extract request from contextrequest object obtainedrequest.user exists?
7Check if request.user is truthyrequest.user = {id:1}true
8Return true from canActivateAccess grantedRoute handler called
💡 Execution stops after canActivate returns true or false, deciding access.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 7Final
requestundefined{ user: undefined }{ user: undefined }{ user: { id: 1 } }{ user: { id: 1 } }
canActivate resultundefinedundefinedfalseundefinedtrue
Key Moments - 3 Insights
Why does canActivate sometimes return false even if the request exists?
Because canActivate checks a condition inside the request, like if request.user exists. The request object always exists, but the user property might be missing, causing false (see execution_table rows 2-4).
What happens if canActivate returns false?
The route handler is NOT called and access is blocked. This is shown in execution_table row 4 where the result is 'Route handler NOT called'.
Can canActivate return a Promise or Observable?
Yes, but in this example it returns a boolean directly. NestJS supports async guards that return Promise<boolean> or Observable<boolean>.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the canActivate result at step 4?
Atrue
Bfalse
Cundefined
Dthrows error
💡 Hint
Check the 'Result' column at step 4 in the execution_table.
At which step does the guard allow the route handler to be called?
AStep 4
BStep 3
CStep 8
DStep 2
💡 Hint
Look for 'Route handler called' in the 'Result' column of execution_table.
If request.user is missing, what will canActivate return?
Afalse
Bthrows error
Ctrue
Dundefined
💡 Hint
See variable_tracker and execution_table rows where request.user is undefined.
Concept Snapshot
Guard interface (canActivate):
- Guards check if a request can proceed.
- canActivate(context) returns true (allow) or false (block).
- Access granted if true, else blocked.
- Can be synchronous or async.
- Used to protect routes in NestJS.
Full Transcript
In NestJS, a Guard is a special class that decides if a request can continue to a route. The key method is canActivate, which receives the request context. Inside canActivate, you check conditions like if the user is logged in. If the check passes, return true to allow access. If not, return false to block. The execution flow starts when a request arrives, NestJS calls canActivate, and based on its boolean result, the route handler runs or not. This example shows canActivate checking if request.user exists. If yes, access is allowed; if no, access is denied. Guards can also return promises or observables for async checks. Understanding this flow helps protect routes easily.