Bird
Raised Fist0
NestJSframework~10 mins

Refresh token pattern in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Refresh token pattern
User logs in
↓
Server issues Access Token + Refresh Token
↓
User uses Access Token to access resources
↓
Access Token expires?
No→Continue using Access Token
Yes↓
User sends Refresh Token to server
↓
Server verifies Refresh Token
↓
Refresh Token valid?
No→Reject request, ask login
Yes↓
Server issues new Access Token (and optionally new Refresh Token)
↓
User continues with new Access Token
This flow shows how a user logs in, gets tokens, uses access token until it expires, then uses refresh token to get a new access token without logging in again.
Execution Sample
NestJS
async refreshToken(oldRefreshToken: string) {
  const user = await this.jwtService.verifyAsync(oldRefreshToken);
  if (!user) throw new UnauthorizedException();
  return this.jwtService.sign({ id: user.id });
}
This function verifies the refresh token and returns a new access token if valid.
Execution Table
StepActionInputCheck/ConditionResult/Output
1User logs inusername/passwordCredentials valid?Issue Access Token + Refresh Token
2User accesses resourceAccess TokenAccess Token valid?Allow access
3Access Token expiresAccess Token expiredExpired?User must refresh token
4User sends Refresh TokenRefresh TokenVerify Refresh TokenValid or Invalid
5Refresh Token validValid Refresh TokenIs token valid?Issue new Access Token
6Refresh Token invalidInvalid Refresh TokenIs token valid?Reject request, ask login
💡 Process stops when refresh token is invalid or user logs out.
Variable Tracker
VariableStartAfter Step 1After Step 4After Step 5Final
accessTokennullissuedexpirednew token issuedvalid
refreshTokennullissuedsent by userverifiedvalid or invalid
usernullauthenticatedextracted from tokenconfirmedauthenticated or rejected
Key Moments - 3 Insights
Why do we need both access and refresh tokens?
Access tokens are short-lived for security; refresh tokens allow getting new access tokens without logging in again, as shown in steps 3 to 5 in the execution_table.
What happens if the refresh token is invalid or expired?
As seen in step 6, the server rejects the request and asks the user to log in again to get new tokens.
Can the refresh token be used to access resources directly?
No, refresh tokens are only for getting new access tokens, not for accessing resources directly, as shown by the separate steps for access token usage and refresh token verification.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does the server verify the refresh token?
AStep 2
BStep 1
CStep 4
DStep 6
💡 Hint
Check the 'Action' and 'Check/Condition' columns in step 4.
According to variable_tracker, what is the state of accessToken after step 5?
Anew token issued
Bnull
Cexpired
Dinvalid
💡 Hint
Look at the 'accessToken' row under 'After Step 5' column.
If the refresh token is invalid, what does the server do according to the execution_table?
AAllow access to resources
BReject request and ask login
CIssue new access token
DIgnore and continue
💡 Hint
See step 6 in the execution_table under 'Result/Output'.
Concept Snapshot
Refresh Token Pattern in NestJS:
- User logs in, gets Access + Refresh Tokens
- Access Token used for resource access
- When Access Token expires, send Refresh Token
- Server verifies Refresh Token
- If valid, server issues new Access Token
- If invalid, user must log in again
- Keeps user logged in securely without frequent logins
Full Transcript
The refresh token pattern helps keep users logged in securely. When a user logs in, the server gives two tokens: an access token and a refresh token. The access token is used to access protected resources but expires quickly for safety. When it expires, the user sends the refresh token to get a new access token without logging in again. The server checks if the refresh token is valid. If yes, it sends a new access token. If not, the user must log in again. This process balances security and convenience.

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