Performance: JWT authentication guard
MEDIUM IMPACT
This concept affects the server response time and client perceived interaction speed by controlling access before route handlers execute.
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; @Injectable() export class JwtAuthGuard implements CanActivate { constructor(private jwtService: JwtService) {} async canActivate(context: ExecutionContext): Promise<boolean> { const request = context.switchToHttp().getRequest(); const token = request.headers['authorization']?.split(' ')[1]; if (!token) return false; try { const decoded = await this.jwtService.verifyAsync(token); request.user = decoded; return true; } catch { return false; } } }
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; import * as jwt from 'jsonwebtoken'; @Injectable() export class JwtAuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); const token = request.headers['authorization']?.split(' ')[1]; if (!token) return false; try { const decoded = jwt.verify(token, 'secret'); request.user = decoded; return true; } catch { return false; } } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous JWT verification in guard | N/A (server-side) | N/A | N/A | [X] Bad |
| Asynchronous JWT verification with JwtService | N/A (server-side) | N/A | N/A | [OK] Good |