Bird
Raised Fist0
NestJSframework~10 mins

Token generation and validation in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Token generation and validation
Start Request
↓
Generate Token
↓
Send Token to Client
↓
Client Sends Token Back
↓
Validate Token
↓
Allow Access
↓
End
This flow shows how a token is created, sent to the client, then validated on future requests to allow or deny access.
Execution Sample
NestJS
const token = this.jwtService.sign(payload);
// send token
const decoded = this.jwtService.verify(token);
if (decoded) {
  // access granted
}
This code generates a token from a payload, then verifies it to check if access should be granted.
Execution Table
StepActionInputOutputNotes
1Generate token{ userId: 1 }eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...Token created from payload
2Send tokenToken stringToken sent to clientClient stores token
3Client sends token backToken stringToken received by serverServer prepares to validate
4Validate tokenToken string{ userId: 1, iat: 1680000000 }Token decoded successfully
5Check validityDecoded payloadAccess grantedToken is valid, user allowed
6Validate tokenInvalid token stringError thrownToken invalid or expired
7Check validityErrorAccess deniedUser denied access due to invalid token
💡 Execution stops when token is either validated successfully or rejected due to invalidity.
Variable Tracker
VariableStartAfter Step 1After Step 4After Step 6
payload{ userId: 1 }{ userId: 1 }{ userId: 1 }{ userId: 1 }
tokenundefinedeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...invalid_token_string
decodedundefinedundefined{ userId: 1, iat: 1680000000 }Error thrown
Key Moments - 3 Insights
Why does the token look like a long random string?
The token is a signed string that encodes the payload securely. See execution_table step 1 where the payload is converted into the token string.
What happens if the token is expired or tampered with?
At step 6 in the execution_table, the validation fails and an error is thrown, leading to access denial at step 7.
Why do we check the decoded payload after verifying the token?
Because verifying the token returns the original payload if valid, which we use to confirm user identity and permissions (step 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at step 4 when validating a valid token?
AError thrown
B{ userId: 1, iat: 1680000000 }
CAccess denied
DToken sent to client
💡 Hint
Check the 'Output' column for step 4 in the execution_table.
At which step does the server deny access due to an invalid token?
AStep 3
BStep 5
CStep 7
DStep 1
💡 Hint
Look for 'Access denied' in the 'Output' column of the execution_table.
If the payload changes, how does it affect the token in variable_tracker after step 1?
AToken string changes to reflect new payload
BToken remains the same
CDecoded payload changes but token stays same
DPayload does not affect token
💡 Hint
Refer to variable_tracker showing token value after step 1 depends on payload.
Concept Snapshot
Token generation and validation in NestJS:
- Use jwtService.sign(payload) to create a token.
- Send token to client for future requests.
- Use jwtService.verify(token) to decode and validate.
- If valid, allow access; if invalid, deny access.
- Tokens secure user identity and session info.
Full Transcript
This visual execution shows how NestJS generates and validates tokens. First, a payload like { userId: 1 } is signed into a token string. This token is sent to the client, who stores it. When the client makes requests, it sends the token back. The server verifies the token. If valid, it decodes the payload and grants access. If invalid or expired, it denies access. Variables like payload, token, and decoded data change step-by-step as shown. Key moments include understanding the token format, handling invalid tokens, and why decoding is needed after verification.

Practice

(1/5)
1. What is the main purpose of generating a token in a NestJS application?
easy
A. To prove a user's identity without sharing their password
B. To store user passwords securely
C. To encrypt the entire database
D. To create a backup of user data

Solution

  1. Step 1: Understand token purpose

    Tokens are used to prove who a user is without sharing sensitive information like passwords.
  2. Step 2: Compare options

    Only To prove a user's identity without sharing their password correctly describes token use; others describe unrelated tasks.
  3. Final Answer:

    To prove a user's identity without sharing their password -> Option A
  4. Quick Check:

    Token purpose = Identity proof without password [OK]
Hint: Tokens prove identity safely without passwords [OK]
Common Mistakes:
  • Thinking tokens store passwords
  • Confusing tokens with database encryption
  • Assuming tokens backup data
2. Which of the following is the correct way to generate a JWT token using the jsonwebtoken package in NestJS?
easy
A. jwt.sign(payload, secretKey, { expiresIn: '1h' })
B. jwt.create(payload, secretKey)
C. jwt.generateToken(secretKey, payload)
D. jwt.verify(payload, secretKey)

Solution

  1. Step 1: Recall JWT token creation syntax

    The sign method creates a token with payload, secret key, and options.
  2. Step 2: Check options

    Only jwt.sign(payload, secretKey, { expiresIn: '1h' }) uses sign correctly with payload, secret, and expiration.
  3. Final Answer:

    jwt.sign(payload, secretKey, { expiresIn: '1h' }) -> Option A
  4. Quick Check:

    Token creation uses sign() method [OK]
Hint: Use jwt.sign() to create tokens with payload and secret [OK]
Common Mistakes:
  • Using jwt.create() which does not exist
  • Mixing order of arguments
  • Using jwt.verify() to create tokens
3. Given the following code snippet in a NestJS service, what will be the output if the token is valid?
const token = jwt.sign({ userId: 123 }, 'secretKey', { expiresIn: '1h' });
const decoded = jwt.verify(token, 'secretKey');
console.log(decoded.userId);
medium
A. undefined
B. null
C. 123
D. Throws an error

Solution

  1. Step 1: Understand token creation and verification

    The token is created with payload { userId: 123 } and signed with 'secretKey'.
  2. Step 2: Verify token with the same secret

    Verification returns the decoded payload, so decoded.userId is 123.
  3. Final Answer:

    123 -> Option C
  4. Quick Check:

    Valid token returns payload userId = 123 [OK]
Hint: Verify returns original payload if token and secret match [OK]
Common Mistakes:
  • Expecting undefined or null instead of payload
  • Using wrong secret causing error
  • Confusing verify with sign
4. Identify the error in this NestJS token validation code:
try {
  const payload = jwt.verify(token, secret);
  return payload.userId;
} catch (error) {
  return 'Invalid token';
}
medium
A. Secret key is not defined
B. Missing async keyword for jwt.verify
C. jwt.verify should be jwt.sign
D. No error, code works correctly

Solution

  1. Step 1: Analyze jwt.verify usage

    jwt.verify is synchronous and used correctly inside try-catch to handle errors.
  2. Step 2: Check for missing elements

    Assuming secret and token are defined, no syntax or logic errors exist.
  3. Final Answer:

    No error, code works correctly -> Option D
  4. Quick Check:

    jwt.verify with try-catch is correct pattern [OK]
Hint: jwt.verify is synchronous; use try-catch for errors [OK]
Common Mistakes:
  • Thinking jwt.verify is async
  • Confusing verify with sign
  • Assuming secret is undefined without context
5. You want to generate a JWT token in NestJS that expires in 30 minutes and includes the user's email and role. Which code snippet correctly achieves this?
hard
A. jwt.sign({ email, role }, secretKey, { expiresAt: '30m' })
B. jwt.sign({ email, role }, secretKey, { expiresIn: '30m' })
C. jwt.sign({ email, role }, secretKey, { expiration: 1800 })
D. jwt.sign({ email, role }, secretKey, { expireIn: 30 })

Solution

  1. Step 1: Recall correct expiration option for jwt.sign

    The option to set token lifetime is expiresIn with string or number format.
  2. Step 2: Validate option values

    Only jwt.sign({ email, role }, secretKey, { expiresIn: '30m' }) uses expiresIn: '30m' correctly; others use invalid keys or formats.
  3. Final Answer:

    jwt.sign({ email, role }, secretKey, { expiresIn: '30m' }) -> Option B
  4. Quick Check:

    Use expiresIn with '30m' for 30 minutes expiry [OK]
Hint: Use expiresIn: '30m' to set 30-minute token expiry [OK]
Common Mistakes:
  • Using expiresAt or expiration instead of expiresIn
  • Passing number without units as string
  • Misspelling expiresIn option
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