Performance: Protected routes with guards
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 |
@UseGuards().import { CanActivate, ExecutionContext } from '@nestjs/common';
export class AlwaysDenyGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
return false;
}
}Applied to a route, what is the result?
import { CanActivate, ExecutionContext } from '@nestjs/common';
export class MyGuard implements CanActivate {
canActivate(context: ExecutionContext) {
if (context.switchToHttp().getRequest().user) {
return true;
}
}
}import { CanActivate, ExecutionContext } from '@nestjs/common';
export class RolesGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const user = request.user;
// Which condition correctly checks for admin role?
}
}role, not an array.user.role === 'admin'. return user && user.roles.includes('admin'); assumes roles is an array, which may be incorrect. Options C and D misuse property types.Pass the test and this pattern moves unknown