Bird
Raised Fist0
NestJSframework~8 mins

Refresh token pattern in NestJS - Performance & Optimization

Choose your learning style10 modes available
Performance: Refresh token pattern
MEDIUM IMPACT
This pattern affects the responsiveness and load of authentication requests, impacting user interaction speed and server load.
Handling user authentication token renewal
NestJS
async function refreshToken(oldToken) {
  // Use async non-blocking verification
  const user = await verifyTokenAsync(oldToken);
  const newToken = generateToken(user);
  return newToken;
}
Async verification frees event loop, allowing concurrent request handling and faster response.
📈 Performance GainNon-blocking, reduces INP by 30-50ms per request
Handling user authentication token renewal
NestJS
async function refreshToken(oldToken) {
  // Synchronously block to verify and generate new token
  const user = verifyTokenSync(oldToken);
  const newToken = generateToken(user);
  return newToken;
}
Synchronous token verification blocks the event loop, causing delays in handling other requests.
📉 Performance CostBlocks event loop for 50-100ms per request, increasing INP and slowing user interactions
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous token verification000[X] Bad
Asynchronous token verification000[OK] Good
Memory bloat from indefinite token storage000[X] Bad
Token storage with expiration and cleanup000[OK] Good
Rendering Pipeline
Refresh token pattern mainly affects server-side request handling and response timing, influencing how fast the browser receives updated tokens and can continue user interactions.
→Request Handling
→Response Generation
→Network Transfer
⚠️ BottleneckRequest Handling when token verification is synchronous or inefficient
Core Web Vital Affected
INP
This pattern affects the responsiveness and load of authentication requests, impacting user interaction speed and server load.
Optimization Tips
1Always use asynchronous methods for token verification to avoid blocking the event loop.
2Implement token expiration and periodic cleanup to maintain stable memory usage.
3Monitor token refresh operations in DevTools Performance panel to detect blocking tasks.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using asynchronous token verification in the refresh token pattern?
AIt prevents blocking the event loop, improving input responsiveness.
BIt reduces the size of the token payload sent to the client.
CIt eliminates the need for token expiration.
DIt increases the number of DOM nodes rendered.
DevTools: Performance
How to check: Record a session while triggering token refresh; look for long tasks or blocking scripts during token verification.
What to look for: Long blocking tasks indicate synchronous operations; shorter, async tasks indicate better performance.

Practice

(1/5)
1. What is the main purpose of using a refresh token in a NestJS authentication system?
easy
A. To store user credentials securely on the client side
B. To replace the access token permanently
C. To issue a new access token without requiring the user to log in again
D. To encrypt the user's password

Solution

  1. Step 1: Understand token roles in authentication

    Access tokens allow access but expire quickly; refresh tokens help get new access tokens without re-login.
  2. Step 2: Identify refresh token purpose

    Refresh tokens are used to request new access tokens after expiration, keeping the user logged in safely.
  3. Final Answer:

    To issue a new access token without requiring the user to log in again -> Option C
  4. Quick Check:

    Refresh token = new access token without re-login [OK]
Hint: Refresh tokens renew access tokens without user login [OK]
Common Mistakes:
  • Confusing refresh token with access token
  • Thinking refresh token stores user credentials
  • Assuming refresh token replaces access token permanently
2. Which of the following is the correct way to verify a refresh token in a NestJS service using JWT?
easy
A. jwtService.verify(refreshToken)
B. jwtService.encrypt(refreshToken)
C. jwtService.decode(accessToken)
D. jwtService.sign(payload)

Solution

  1. Step 1: Identify JWT methods for token verification

    In NestJS, jwtService.verify() checks token validity and signature.
  2. Step 2: Match method to refresh token verification

    To verify a refresh token, use jwtService.verify(refreshToken) to confirm it is valid and not expired.
  3. Final Answer:

    jwtService.verify(refreshToken) -> Option A
  4. Quick Check:

    Verify token = jwtService.verify() [OK]
Hint: Use jwtService.verify() to check token validity [OK]
Common Mistakes:
  • Using sign() instead of verify() to check tokens
  • Using decode() which does not verify signature
  • Trying to encrypt tokens with jwtService
3. Given this NestJS code snippet, what will be the output if the refresh token is valid?
async refreshToken(token: string) {
  try {
    const payload = this.jwtService.verify(token);
    const newAccessToken = this.jwtService.sign({ userId: payload.sub });
    return { accessToken: newAccessToken };
  } catch (e) {
    throw new UnauthorizedException('Invalid refresh token');
  }
}
medium
A. Throws UnauthorizedException with message 'Invalid refresh token'
B. { accessToken: 'newly_generated_token_string' }
C. Returns the original refresh token
D. Returns null

Solution

  1. Step 1: Analyze token verification

    The code verifies the refresh token; if valid, it extracts the payload.
  2. Step 2: Generate new access token

    Using the payload's user ID, it signs a new access token and returns it in an object.
  3. Final Answer:

    { accessToken: 'newly_generated_token_string' } -> Option B
  4. Quick Check:

    Valid refresh token returns new access token [OK]
Hint: Valid token returns new access token object [OK]
Common Mistakes:
  • Assuming it returns the refresh token again
  • Thinking it throws error on valid token
  • Expecting null instead of token object
4. Identify the bug in this NestJS refresh token handler:
async refreshToken(token: string) {
  const payload = this.jwtService.verify(token);
  const newAccessToken = this.jwtService.sign({ userId: payload.userId });
  return { accessToken: newAccessToken };
}
medium
A. Missing try-catch block to handle invalid tokens
B. Using sign() instead of verify() for token validation
C. Returning access token as a string instead of an object
D. Incorrect property name 'userId' instead of 'sub' in payload

Solution

  1. Step 1: Check payload property usage

    JWT payload usually stores user ID in 'sub' property, not 'userId'.
  2. Step 2: Identify mismatch causing error

    Accessing 'payload.userId' will be undefined, causing incorrect token signing.
  3. Final Answer:

    Incorrect property name 'userId' instead of 'sub' in payload -> Option D
  4. Quick Check:

    JWT user ID = payload.sub, not payload.userId [OK]
Hint: Check JWT payload keys carefully (usually 'sub') [OK]
Common Mistakes:
  • Ignoring missing try-catch for errors
  • Assuming payload uses 'userId' key
  • Confusing sign() and verify() methods
5. You want to implement a refresh token system in NestJS that invalidates old refresh tokens after use. Which approach correctly achieves this?
hard
A. Store refresh tokens in a database and delete the old token when issuing a new one
B. Generate refresh tokens without storing them and rely on JWT expiration only
C. Use the same refresh token indefinitely without expiration
D. Send the access token as the refresh token

Solution

  1. Step 1: Understand token invalidation

    To invalidate old refresh tokens, you must track them server-side, usually in a database.
  2. Step 2: Implement token replacement logic

    When issuing a new refresh token, delete or mark the old one invalid in the database to prevent reuse.
  3. Final Answer:

    Store refresh tokens in a database and delete the old token when issuing a new one -> Option A
  4. Quick Check:

    Invalidate old tokens by storing and deleting them [OK]
Hint: Track refresh tokens server-side to invalidate old ones [OK]
Common Mistakes:
  • Not storing tokens, so can't invalidate old ones
  • Using refresh tokens without expiration
  • Confusing access token with refresh token
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard