Performance: Combining multiple guards
MEDIUM IMPACT
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 |