Performance: Protected routes with guards
MEDIUM IMPACT
This concept affects the server response time and initial page load speed by adding authorization checks before route handlers execute.
import { CanActivate, ExecutionContext, Injectable, UseGuards, Controller, Get } from '@nestjs/common'; @Injectable() export class AuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); return !!request.user; } } @Controller() export class ProfileController { @UseGuards(AuthGuard) @Get('/profile') getProfile() { // handle profile } }
app.get('/profile', (req, res) => { if (!req.user) { res.status(401).send('Unauthorized'); return; } // handle profile });
| Pattern | Server Processing | Authorization Checks | Response Delay | Verdict |
|---|---|---|---|---|
| Inline auth checks in routes | Repeated per route | Multiple redundant checks | Higher delay per request | [X] Bad |
| Centralized guards | Single reusable check | One check per request | Minimal added delay | [OK] Good |