Performance: Guard binding levels
MEDIUM IMPACT
This affects the request processing speed and server response time by controlling how often guards run during request handling.
import { Injectable, CanActivate, ExecutionContext, Controller, UseGuards } from '@nestjs/common'; @Injectable() export class AuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { // auth logic return true; } } // Binding guard only on specific controllers or routes @Controller('users') @UseGuards(AuthGuard) export class UsersController {}
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; @Injectable() export class AuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { // heavy auth logic return true; } } // Binding guard globally in main.ts app.useGlobalGuards(new AuthGuard());
| Pattern | Guard Executions | CPU Usage | Response Delay | Verdict |
|---|---|---|---|---|
| Global guard binding | Runs on all requests | High | Increased latency | [X] Bad |
| Controller-level guard binding | Runs on specific controllers | Medium | Moderate latency | [!] OK |
| Method-level guard binding | Runs only on specific routes | Low | Minimal latency | [OK] Good |