Concept Flow - Combining multiple guards
Request comes in
Guard 1 runs
Guard 2 runs
The request passes through Guard 1 first. If it passes, Guard 2 runs. If all guards pass, access is allowed; if any guard fails, the request is rejected.
import { UseGuards } from '@nestjs/common'; import { Controller, Get } from '@nestjs/common'; @Controller() export class AppController { @UseGuards(AuthGuard, RolesGuard) @Get('profile') getProfile() { return 'User Profile'; } }
| Step | Guard | Guard Result | Action | Request Outcome |
|---|---|---|---|---|
| 1 | AuthGuard | Pass | Continue to next guard | Pending |
| 2 | RolesGuard | Pass | Allow access | Access granted |
| 3 | End | - | - | Request handled successfully |
| Variable | Start | After AuthGuard | After RolesGuard | Final |
|---|---|---|---|---|
| requestAllowed | false | true | true | true |
Use @UseGuards(Guard1, Guard2) to combine guards. Guards run in order; if any guard returns false, request is denied. All guards must pass to allow access. Useful for layered security checks. Easy to add or remove guards as needed.
What happens when you use @UseGuards(AuthGuard, RolesGuard) on a NestJS route handler?
Choose the best description.
@UseGuards(), NestJS runs them in sequence and requires all to approve access.AuthGuard and RolesGuard must return true for the request to proceed.Which of the following is the correct syntax to apply two guards AuthGuard and RolesGuard on a controller method?
?@UseGuards(), separated by commas.Given the following code snippet, what will be the output when a request is made?
@UseGuards(AuthGuard, RolesGuard)
@Get('profile')
getProfile() {
return 'User Profile';
}
// AuthGuard returns true
// RolesGuard returns false
AuthGuard returns true but RolesGuard returns false, so access is denied and an exception is thrown.Identify the error in this NestJS controller snippet using multiple guards:
@UseGuards(AuthGuard RolesGuard)
@Get('data')
getData() {
return 'Data';
}
@UseGuards() must be separated by commas.AuthGuard and RolesGuard, causing a syntax error.You want to protect a route so that only authenticated users with the role 'admin' can access it. You have AuthGuard and RolesGuard available. How should you combine them in your controller method?
@UseGuards(). Order matters: AuthGuard first authenticates and sets req.user, then RolesGuard checks the role.Pass the test and this pattern moves unknown