Discover how a simple token can protect your app and make user login smooth and secure!
Why Token generation and validation in NestJS? - Purpose & Use Cases
Imagine building a web app where users log in, and you manually check their username and password on every request without any token.
You have to write code to remember who is logged in, check passwords again and again, and keep track of sessions yourself.
This manual way is slow and risky. You might forget to check if a user is logged in, or accidentally expose sensitive data.
It's hard to keep track of users safely, and your code becomes messy and full of repeated checks.
Token generation and validation create a secure, automatic way to prove who a user is.
Once a user logs in, the system gives them a token. This token is like a secret badge that proves their identity without checking passwords every time.
The system can quickly check the token's validity, making your app safer and faster.
if (req.session.user && req.session.user.isLoggedIn) { /* allow access */ } else { /* deny */ }
const token = generateToken(user); verifyToken(token); // access granted if validThis lets your app securely recognize users across many requests without slowing down or risking security.
Think of an online store where you log in once, and your token keeps you logged in while you browse, add items to your cart, and checkout safely.
Manual user checks are slow and error-prone.
Tokens act like secure badges proving user identity.
Token validation makes apps faster, safer, and easier to build.
Practice
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 AQuick Check:
Token purpose = Identity proof without password [OK]
- Thinking tokens store passwords
- Confusing tokens with database encryption
- Assuming tokens backup data
jsonwebtoken package in NestJS?Solution
Step 1: Recall JWT token creation syntax
Thesignmethod creates a token with payload, secret key, and options.Step 2: Check options
Only jwt.sign(payload, secretKey, { expiresIn: '1h' }) usessigncorrectly with payload, secret, and expiration.Final Answer:
jwt.sign(payload, secretKey, { expiresIn: '1h' }) -> Option AQuick Check:
Token creation uses sign() method [OK]
- Using jwt.create() which does not exist
- Mixing order of arguments
- Using jwt.verify() to create tokens
const token = jwt.sign({ userId: 123 }, 'secretKey', { expiresIn: '1h' });
const decoded = jwt.verify(token, 'secretKey');
console.log(decoded.userId);Solution
Step 1: Understand token creation and verification
The token is created with payload { userId: 123 } and signed with 'secretKey'.Step 2: Verify token with the same secret
Verification returns the decoded payload, so decoded.userId is 123.Final Answer:
123 -> Option CQuick Check:
Valid token returns payload userId = 123 [OK]
- Expecting undefined or null instead of payload
- Using wrong secret causing error
- Confusing verify with sign
try {
const payload = jwt.verify(token, secret);
return payload.userId;
} catch (error) {
return 'Invalid token';
}Solution
Step 1: Analyze jwt.verify usage
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 DQuick Check:
jwt.verify with try-catch is correct pattern [OK]
- Thinking jwt.verify is async
- Confusing verify with sign
- Assuming secret is undefined without context
Solution
Step 1: Recall correct expiration option for jwt.sign
The option to set token lifetime isexpiresInwith string or number format.Step 2: Validate option values
Only jwt.sign({ email, role }, secretKey, { expiresIn: '30m' }) usesexpiresIn: '30m'correctly; others use invalid keys or formats.Final Answer:
jwt.sign({ email, role }, secretKey, { expiresIn: '30m' }) -> Option BQuick Check:
Use expiresIn with '30m' for 30 minutes expiry [OK]
- Using expiresAt or expiration instead of expiresIn
- Passing number without units as string
- Misspelling expiresIn option
Ready to prove it?
Pass the test and this pattern moves unknown
