0
0
NestJSframework~8 mins

JWT strategy in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: JWT strategy
MEDIUM IMPACT
This affects the server-side authentication process and the client-server communication speed during token validation.
Validating user authentication with JWT in a NestJS app
NestJS
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 });
  }
}
Avoids blocking the event loop by using asynchronous, lightweight validation and environment variables for secrets.
📈 Performance GainNon-blocking validation improves INP and reduces server response latency.
Validating user authentication with JWT in a NestJS app
NestJS
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 };
  }
}
The validate method blocks the event loop with a heavy synchronous operation, causing slow response and poor interaction performance.
📉 Performance CostBlocks event loop for hundreds of milliseconds, increasing INP and server response time.
Performance Comparison
PatternServer BlockingEvent Loop ImpactResponse LatencyVerdict
Synchronous heavy validationBlocks server threadBlocks event loopHigh latency[X] Bad
Asynchronous lightweight validationNon-blockingEvent loop freeLow latency[OK] Good
Rendering Pipeline
JWT strategy runs on the server before responding to client requests. It impacts the server's ability to quickly validate tokens and send responses, affecting interaction responsiveness.
Server Processing
Network Response
⚠️ BottleneckBlocking synchronous operations in token validation delay server response.
Core Web Vital Affected
INP
This affects the server-side authentication process and the client-server communication speed during token validation.
Optimization Tips
1Avoid heavy synchronous operations in JWT validation to keep the event loop free.
2Use environment variables for JWT secrets to improve security and deployment speed.
3Keep JWT payloads small and validation logic lightweight to reduce server response time.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of using synchronous heavy computation in JWT validation?
AIt increases the size of the JWT token.
BIt blocks the event loop, causing slow server responses.
CIt causes layout shifts in the browser.
DIt improves token security.
DevTools: Network and Performance panels
How to check: Use Network panel to measure server response time for authenticated requests. Use Performance panel to check main thread blocking time during validation.
What to look for: Look for long server response times and main thread blocking events indicating slow JWT validation.