Performance: Why guards control access
MEDIUM IMPACT
Guards affect the speed of request handling by controlling access before route handlers run, impacting server response time and user experience.
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; @Injectable() export class FastGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { // Simple, fast check const request = context.switchToHttp().getRequest(); return Boolean(request.headers['authorization']); } }
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; @Injectable() export class SlowGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { // Simulate heavy synchronous processing for (let i = 0; i < 1e8; i++) {} return true; } }
| Pattern | CPU Usage | Event Loop Blocking | Response Delay | Verdict |
|---|---|---|---|---|
| Heavy synchronous guard logic | High | Yes, blocks event loop | High delay | [X] Bad |
| Lightweight guard with simple checks | Low | No | Minimal delay | [OK] Good |