Performance: Combining multiple guards
This affects the request processing speed and server response time by adding multiple authorization checks before route handlers execute.
import { CanActivate, ExecutionContext, Injectable, UseGuards, Get } from '@nestjs/common'; @Injectable() export class CombinedGuard implements CanActivate { constructor( private authGuard: AuthGuard, private rolesGuard: RolesGuard ) {} async canActivate(context: ExecutionContext) { const auth = await this.authGuard.canActivate(context); if (!auth) return false; const roles = await this.rolesGuard.canActivate(context); return roles; } } // In controller @UseGuards(CombinedGuard) @Get('profile') getProfile() { return {}; }
import { CanActivate, ExecutionContext, Injectable, UseGuards, Get } from '@nestjs/common'; @Injectable() export class AuthGuard implements CanActivate { canActivate(context: ExecutionContext) { // auth logic return true; } } @Injectable() export class RolesGuard implements CanActivate { canActivate(context: ExecutionContext) { // role check logic return true; } } // In controller @UseGuards(AuthGuard, RolesGuard, AnotherGuard, YetAnotherGuard) @Get('profile') getProfile() { return {}; }
| Pattern | Guard Calls | Sequential Checks | CPU Time | Verdict |
|---|---|---|---|---|
| Multiple separate guards | N calls | N sequential | Higher CPU time | [X] Bad |
| Single combined guard | 1 call | Optimized sequential | Lower CPU time | [OK] Good |
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