0
0
NestJSframework~10 mins

Role-based guards in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Role-based guards
Request comes in
Guard checks user roles
Has Role
Allow
Controller
The guard intercepts a request, checks if the user has the required role, then allows or denies access accordingly.
Execution Sample
NestJS
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
@Injectable()
export class RolesGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    return user?.roles?.includes('admin');
  }
}
This guard checks if the user has the 'admin' role to allow access.
Execution Table
StepActionUser RolesConditionResult
1Request received['user', 'admin']Check if 'admin' in rolesTrue
2Guard allows access['user', 'admin']Return trueAccess granted
3Request received['user']Check if 'admin' in rolesFalse
4Guard denies access['user']Return falseAccess denied
💡 Execution stops after guard returns true or false to allow or deny access.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
user.rolesundefined['user', 'admin']['user', 'admin']['user']['user']
condition ('admin' in roles)undefinedtruetruefalsefalse
guard resultundefinedundefinedtrueundefinedfalse
Key Moments - 2 Insights
Why does the guard deny access even if the user has other roles?
The guard specifically checks for the 'admin' role only (see execution_table step 3 and 4). If 'admin' is missing, it denies access regardless of other roles.
What happens if the user object is missing roles?
If user.roles is undefined, the guard will throw an error or deny access because it cannot find 'admin' in roles. Always ensure roles exist before checking.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the guard result at step 2?
Afalse
Btrue
Cundefined
Dthrows error
💡 Hint
Check the 'guard result' column after step 2 in variable_tracker.
At which step does the guard deny access?
AStep 4
BStep 2
CStep 1
DStep 3
💡 Hint
Look at the 'Result' column in execution_table for 'Access denied'.
If the user roles were ['admin', 'editor'], how would the condition in step 1 evaluate?
AFalse
BUndefined
CTrue
DError
💡 Hint
The condition checks if 'admin' is included in roles array.
Concept Snapshot
Role-based guards in NestJS check user roles before allowing access.
Use canActivate method to inspect request user roles.
Return true to allow, false to deny.
Ensure user roles exist to avoid errors.
Common pattern: user.roles.includes('requiredRole').
Full Transcript
Role-based guards in NestJS work by intercepting incoming requests and checking if the user has the required role to access a resource. The guard uses the canActivate method to get the request and user roles. It then checks if the required role, such as 'admin', is present in the user's roles array. If yes, it returns true and allows access to the controller. If not, it returns false and denies access. The execution table shows steps where the guard checks roles and decides access. Variables like user.roles and the guard result change during execution. Beginners often get confused why access is denied if the user has other roles or if roles are missing. The guard strictly checks for the required role only. This visual trace helps understand how role-based guards control access in NestJS.