Performance: JWT authentication guard
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 |
canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
const authHeader = request.headers['authorization'];
if (!authHeader) {
throw new UnauthorizedException('No token provided');
}
// further token validation...
return true;
}async canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
const token = request.headers['authorization']?.split(' ')[1];
if (!token) return false;
try {
const payload = await this.jwtService.verifyAsync(token);
request.user = payload;
} catch {
return true;
}
return true;
}isAdmin based on the user's role. Which approach correctly extends the default JWT guard to achieve this?Pass the test and this pattern moves unknown