Performance: JWT strategy
This affects the server-side authentication process and the client-server communication speed during token validation.
import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy, ExtractJwt } from 'passport-jwt'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: process.env.JWT_SECRET, }); } async validate(payload: any) { // Lightweight async validation return Promise.resolve({ userId: payload.sub, username: payload.username }); } }
import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy, ExtractJwt } from 'passport-jwt'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: 'hardcoded_secret', }); } async validate(payload: any) { // Heavy synchronous operation here for (let i = 0; i < 1000000000; i++) {} return { userId: payload.sub, username: payload.username }; } }
| Pattern | Server Blocking | Event Loop Impact | Response Latency | Verdict |
|---|---|---|---|---|
| Synchronous heavy validation | Blocks server thread | Blocks event loop | High latency | [X] Bad |
| Asynchronous lightweight validation | Non-blocking | Event loop free | Low latency | [OK] Good |
async validate(payload: any) {
return { id: payload.userId, name: payload.username };
}constructor(private readonly jwtService: JwtService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
});
}Pass the test and this pattern moves unknown