Bird
Raised Fist0
Node.jsframework~20 mins

JWT token generation and verification in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
JWT Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this JWT token verification code?
Consider this Node.js code using the jsonwebtoken library. What will be logged to the console?
Node.js
import jwt from 'jsonwebtoken';

const secret = 'mysecret';
const token = jwt.sign({ userId: 123 }, secret, { expiresIn: '1h' });

try {
  const decoded = jwt.verify(token, secret);
  console.log(decoded.userId);
} catch (err) {
  console.log('Invalid token');
}
A123
BInvalid token
CSyntaxError
Dundefined
Attempts:
2 left
💡 Hint
The token is signed and verified with the same secret and is not expired.
❓ component_behavior
intermediate
2:00remaining
What happens if you verify a JWT token with the wrong secret?
Given this code snippet, what will be the console output?
Node.js
import jwt from 'jsonwebtoken';

const secret = 'correctsecret';
const wrongSecret = 'wrongsecret';
const token = jwt.sign({ role: 'admin' }, secret);

try {
  const decoded = jwt.verify(token, wrongSecret);
  console.log(decoded.role);
} catch (error) {
  console.log(error.name);
}
ATokenExpiredError
Badmin
Cundefined
DJsonWebTokenError
Attempts:
2 left
💡 Hint
The secret used to verify must match the secret used to sign.
📝 Syntax
advanced
2:00remaining
Which option correctly generates a JWT token with an expiration of 2 hours?
Choose the code snippet that correctly creates a JWT token with a 2-hour expiration using jsonwebtoken.
Ajwt.sign({ id: 1 }, 'secret', { expiration: 7200 })
Bjwt.sign({ id: 1 }, 'secret', { expiresIn: '2h' })
Cjwt.sign({ id: 1 }, 'secret', { expireIn: 2 })
Djwt.sign({ id: 1 }, 'secret', { expires: '2hours' })
Attempts:
2 left
💡 Hint
Check the exact option name and value format for expiration in jsonwebtoken.
🔧 Debug
advanced
2:00remaining
Why does this JWT verification code throw an error?
Examine the code and select the reason for the error thrown during verification.
Node.js
import jwt from 'jsonwebtoken';

const secret = 'topsecret';
const token = jwt.sign({ name: 'Alice' }, secret);

const decoded = jwt.verify(token);
console.log(decoded.name);
AMissing secret argument in jwt.verify causes an error
BToken is expired
CPayload is empty
Djwt.sign syntax is incorrect
Attempts:
2 left
💡 Hint
jwt.verify requires the token and the secret to verify the signature.
🧠 Conceptual
expert
2:00remaining
What is the main security risk if you expose your JWT secret key publicly?
Select the best explanation for the risk of exposing your JWT secret key.
AUsers will lose their passwords
BTokens will expire immediately
CAttackers can create valid tokens and impersonate users
DThe server will reject all tokens
Attempts:
2 left
💡 Hint
Think about what the secret key is used for in JWT.

Practice

(1/5)
1. What is the main purpose of a JWT token in a Node.js application?
easy
A. To securely transmit user identity without sending passwords repeatedly
B. To store user passwords in the database
C. To encrypt all user data on the server
D. To create a permanent session without expiration

Solution

  1. Step 1: Understand JWT token purpose

    JWT tokens are used to prove user identity securely without sending passwords every time.
  2. Step 2: Compare options

    Only To securely transmit user identity without sending passwords repeatedly correctly describes this purpose; others describe unrelated or incorrect uses.
  3. Final Answer:

    To securely transmit user identity without sending passwords repeatedly -> Option A
  4. Quick Check:

    JWT purpose = Secure identity proof [OK]
Hint: JWT = identity proof without password resend [OK]
Common Mistakes:
  • Thinking JWT stores passwords
  • Confusing JWT with encryption of all data
  • Assuming JWT creates permanent sessions
2. Which of the following is the correct syntax to generate a JWT token using the jsonwebtoken library in Node.js?
easy
A. jwt.generate(payload, secretKey, { expiresAt: '1h' })
B. jwt.create(payload, secretKey, { expiresIn: '1h' })
C. jwt.sign(payload, secretKey, { expiresIn: '1h' })
D. jwt.make(payload, secretKey, { expire: '1h' })

Solution

  1. Step 1: Recall jsonwebtoken method for token creation

    The correct method to create a token is jwt.sign with payload, secret, and options.
  2. Step 2: Check option syntax

    Only jwt.sign(payload, secretKey, { expiresIn: '1h' }) uses jwt.sign and correct option key expiresIn; others use invalid method names or option keys.
  3. Final Answer:

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

    Token creation method = jwt.sign [OK]
Hint: Use jwt.sign() with expiresIn option for token creation [OK]
Common Mistakes:
  • Using wrong method names like create or generate
  • Using expiresAt or expire instead of expiresIn
  • Missing the secret key argument
3. Given the code snippet:
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 123 }, 'secret123', { expiresIn: '2h' });
const decoded = jwt.verify(token, 'secret123');
console.log(decoded.userId);

What will be the output when this code runs?
medium
A. 123
B. undefined
C. Error: invalid token
D. null

Solution

  1. Step 1: Understand token creation and verification

    The token is created with payload { userId: 123 } and secret 'secret123', then verified with the same secret.
  2. Step 2: Check decoded payload output

    jwt.verify returns the original payload if token is valid, so decoded.userId is 123.
  3. Final Answer:

    123 -> Option A
  4. Quick Check:

    Decoded userId = 123 [OK]
Hint: Verify with same secret returns original payload [OK]
Common Mistakes:
  • Expecting undefined or null instead of payload
  • Using different secret causing invalid token error
  • Not understanding jwt.verify returns payload
4. Identify the error in this JWT verification code snippet:
const jwt = require('jsonwebtoken');
const token = jwt.sign({ id: 1 }, 'mysecret');
const decoded = jwt.verify(token, 'wrongsecret');
console.log(decoded.id);
medium
A. Token is expired
B. jwt.sign method is used incorrectly
C. Payload is missing id property
D. Secret key used for verification is incorrect

Solution

  1. Step 1: Check token creation and verification secrets

    Token is signed with 'mysecret' but verified with 'wrongsecret', causing verification failure.
  2. Step 2: Understand jwt.verify behavior on secret mismatch

    jwt.verify throws an error if secret does not match, so decoded.id is not accessible.
  3. Final Answer:

    Secret key used for verification is incorrect -> Option D
  4. Quick Check:

    Secret mismatch = verification error [OK]
Hint: Verify with same secret as sign to avoid errors [OK]
Common Mistakes:
  • Assuming token expired without expiration set
  • Thinking payload lacks id property
  • Misusing jwt.sign method syntax
5. You want to generate a JWT token that expires in 30 minutes and includes the user's email and role. Which code snippet correctly does this using the jsonwebtoken library?
hard
A. jwt.sign({ email: user.email, role: user.role }, 'secretKey', { expire: 1800 })
B. jwt.sign({ email: user.email, role: user.role }, 'secretKey', { expiresIn: '30m' })
C. jwt.sign({ email: user.email, role: user.role }, 'secretKey', { expiresAt: '30min' })
D. jwt.sign({ email: user.email, role: user.role }, 'secretKey', { timeout: '30m' })

Solution

  1. Step 1: Identify correct payload and expiration option

    The payload includes email and role, and expiration uses expiresIn with '30m' for 30 minutes.
  2. Step 2: Validate option keys and values

    Only jwt.sign({ email: user.email, role: user.role }, 'secretKey', { expiresIn: '30m' }) uses correct option key expiresIn and valid time format '30m'; others use invalid keys or formats.
  3. Final Answer:

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

    expiresIn '30m' = 30 minutes expiry [OK]
Hint: Use expiresIn: '30m' for 30-minute token expiry [OK]
Common Mistakes:
  • Using expire or expiresAt instead of expiresIn
  • Wrong time format like '30min'
  • Using timeout option which is invalid
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