📖 Scenario: You are building a simple authentication system in a NestJS backend. You need to create a token generation and validation mechanism to securely identify users.
🎯 Goal: Build a NestJS service that generates a JWT token for a user ID and validates the token to extract the user ID.
📋 What You'll Learn
Create a service with a method to generate a JWT token using a secret key
Create a method to validate the JWT token and extract the user ID
Use the @nestjs/jwt package for token operations
Use a fixed secret key 'mySecretKey' for signing tokens
Use a payload with a userId property
💡 Why This Matters
🌍 Real World
Token generation and validation is essential for user authentication in web applications, allowing secure access control.
💼 Career
Understanding JWT handling in NestJS is a common requirement for backend developer roles working with modern authentication systems.
Progress0 / 4 steps
1
Setup JWT service and secret key
Create a NestJS service class called AuthService. Inside it, create a private readonly property called jwtSecret and set it to the string 'mySecretKey'.
NestJS
Hint
Define a class named AuthService and add a private readonly property jwtSecret with the value 'mySecretKey'.
2
Add token generation method
Inside the AuthService class, add a method called generateToken that takes a parameter userId of type string. Use the sign method from @nestjs/jwt to create a JWT token with a payload containing { userId } and sign it with this.jwtSecret. Return the generated token.
NestJS
Hint
Use the sign function from @nestjs/jwt to create a token with the payload { userId } and sign it using this.jwtSecret.
3
Add token validation method
Inside the AuthService class, add a method called validateToken that takes a parameter token of type string. Use the verify method from @nestjs/jwt to verify the token with this.jwtSecret. Return the userId from the decoded payload.
NestJS
Hint
Use the verify function from @nestjs/jwt to decode the token and extract the userId.
4
Export AuthService and finalize
Add an export statement to export the AuthService class so it can be used in other parts of the application.
NestJS
Hint
Use export { AuthService }; to export the class.
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
Step 1: Understand token purpose
Tokens are used to prove who a user is without sharing sensitive information like passwords.
Step 2: Compare options
Only To prove a user's identity without sharing their password correctly describes token use; others describe unrelated tasks.
Final Answer:
To prove a user's identity without sharing their password -> Option A
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
Step 1: Recall JWT token creation syntax
The sign method creates a token with payload, secret key, and options.
Step 2: Check options
Only jwt.sign(payload, secretKey, { expiresIn: '1h' }) uses sign correctly with payload, secret, and expiration.
Final Answer:
jwt.sign(payload, secretKey, { expiresIn: '1h' }) -> Option A
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?
jwt.verify is synchronous and used correctly inside try-catch to handle errors.
Step 2: Check for missing elements
Assuming secret and token are defined, no syntax or logic errors exist.
Final Answer:
No error, code works correctly -> Option D
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
Step 1: Recall correct expiration option for jwt.sign
The option to set token lifetime is expiresIn with string or number format.
Step 2: Validate option values
Only jwt.sign({ email, role }, secretKey, { expiresIn: '30m' }) uses expiresIn: '30m' correctly; others use invalid keys or formats.
Final Answer:
jwt.sign({ email, role }, secretKey, { expiresIn: '30m' }) -> Option B
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 unknownstrongwhile earning +1 Grip toward your certificate.