Concept Flow - Why guards control access
Request Received
Guard Checks Conditions
Allow
Controller Executes
When a request comes in, the guard checks if access is allowed. If yes, the controller runs. If no, access is denied.
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
return request.user?.isAdmin === true;
}| Step | Action | Input | Condition Checked | Result | Next Step |
|---|---|---|---|---|---|
| 1 | Receive request | { user: { isAdmin: true } } | N/A | N/A | Check guard |
| 2 | Guard reads user | { isAdmin: true } | user.isAdmin === true | True | Allow access |
| 3 | Controller runs | N/A | N/A | Request processed | Send response |
| 4 | Receive request | { user: { isAdmin: false } } | N/A | N/A | Check guard |
| 5 | Guard reads user | { isAdmin: false } | user.isAdmin === true | False | Deny access |
| 6 | Send error | N/A | N/A | 403 Forbidden | End |
| Variable | Start | After Step 2 | After Step 5 | Final |
|---|---|---|---|---|
| request.user.isAdmin | undefined | true | false | N/A |
| canActivate result | undefined | true | false | N/A |
Guards in NestJS check conditions before a controller runs. They return true to allow access or false to deny it. Guards control who can use routes. They help protect resources by blocking unauthorized requests. Use canActivate method to define guard logic.