Performance: Token generation and validation
This affects page load speed and interaction responsiveness by controlling how quickly tokens are generated and validated during user authentication.
import { Injectable } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; @Injectable() export class AuthService { constructor(private jwtService: JwtService) {} async generateToken(user: any) { return await this.jwtService.signAsync(user, { expiresIn: '1h' }); } async validateToken(token: string) { try { return await this.jwtService.verifyAsync(token); } catch { return null; } } }
import * as jwt from 'jsonwebtoken'; function generateToken(user) { return jwt.sign(user, 'secretKey', { expiresIn: '1h' }); } function validateToken(token) { try { return jwt.verify(token, 'secretKey'); } catch (e) { return null; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous token generation/validation | 0 (server-side) | 0 | 0 | [X] Bad |
| Asynchronous token generation/validation | 0 (server-side) | 0 | 0 | [OK] Good |
jsonwebtoken package in NestJS?sign method creates a token with payload, secret key, and options.sign correctly with payload, secret, and expiration.const token = jwt.sign({ userId: 123 }, 'secretKey', { expiresIn: '1h' });
const decoded = jwt.verify(token, 'secretKey');
console.log(decoded.userId);try {
const payload = jwt.verify(token, secret);
return payload.userId;
} catch (error) {
return 'Invalid token';
}expiresIn with string or number format.expiresIn: '30m' correctly; others use invalid keys or formats.Pass the test and this pattern moves unknown