Bird
Raised Fist0
Expressframework~20 mins

JWT token creation in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
JWT Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this JWT token creation code?
Consider this Express route that creates a JWT token. What will be the response body when a POST request is made with {"userId": "123"}?
Express
import express from 'express';
import jwt from 'jsonwebtoken';

const app = express();
app.use(express.json());

app.post('/login', (req, res) => {
  const { userId } = req.body;
  const token = jwt.sign({ id: userId }, 'secretKey', { expiresIn: '1h' });
  res.json({ token });
});
ASyntaxError
BTypeError
C{"error": "Invalid userId"}
D{"token": "<a valid JWT token string>"}
Attempts:
2 left
💡 Hint
The jwt.sign method returns a string token when called correctly.
📝 Syntax
intermediate
1:30remaining
Which option correctly creates a JWT token with payload {id: 5} and secret 'key'?
Choose the code snippet that correctly creates a JWT token using jsonwebtoken in Express.
Ajwt.sign(id: 5, 'key')
Bjwt.sign({ id: 5 }, 'key')
Cjwt.sign({id: 5}, key)
Djwt.sign({ id: 5 }, 'key', expiresIn: '1h')
Attempts:
2 left
💡 Hint
The payload must be an object, and the secret a string.
🔧 Debug
advanced
2:00remaining
What error does this JWT token creation code raise?
Analyze the code below. What error will occur when this Express route is called?
Express
app.post('/token', (req, res) => {
  const token = jwt.sign({ user: req.body.user });
  res.send(token);
});
ATypeError: secretOrPrivateKey must have a value
BSyntaxError: Unexpected token
CReferenceError: jwt is not defined
DNo error, returns a token string
Attempts:
2 left
💡 Hint
jwt.sign requires a secret string as second argument.
state_output
advanced
2:00remaining
What is the value of 'decoded' after verifying this JWT token?
Given this code snippet, what will be the value of 'decoded' if the token is valid?
Express
const token = jwt.sign({ id: 10, role: 'admin' }, 'mySecret');
const decoded = jwt.verify(token, 'mySecret');
ASyntaxError
B{ id: 10, role: 'admin' }
C{ id: 10, role: 'admin', iat: <number> }
Dnull
Attempts:
2 left
💡 Hint
jwt.verify returns the payload plus issued at timestamp.
🧠 Conceptual
expert
2:30remaining
Which option best explains why JWT tokens include a secret key during creation?
Why do we provide a secret key when creating a JWT token with jwt.sign?
ATo sign the token so its integrity can be verified
BTo encrypt the token so only the server can read it
CTo store user data securely inside the token
DTo make the token expire automatically
Attempts:
2 left
💡 Hint
Think about what signing a token means.

Practice

(1/5)
1. What is the main purpose of creating a JWT token in an Express app?
easy
A. To connect to a database
B. To style the user interface
C. To handle file uploads
D. To securely store user information for authentication

Solution

  1. Step 1: Understand JWT token role

    JWT tokens are used to safely store user data for verifying identity.
  2. Step 2: Identify correct purpose

    Among the options, only storing user info for authentication matches JWT's role.
  3. Final Answer:

    To securely store user information for authentication -> Option D
  4. Quick Check:

    JWT purpose = Authentication [OK]
Hint: JWT tokens are for authentication, not UI or database [OK]
Common Mistakes:
  • Confusing JWT with UI styling or database connection
  • Thinking JWT handles file uploads
2. Which of the following is the correct syntax to create a JWT token using the jsonwebtoken package in Express?
easy
A. jwt.generate(payload, secretKey, { expiresIn: '1h' })
B. jwt.create(payload, secretKey, { expiresIn: '1h' })
C. jwt.sign(payload, secretKey, { expiresIn: '1h' })
D. jwt.make(payload, secretKey, { expiresIn: '1h' })

Solution

  1. Step 1: Recall jsonwebtoken method

    The correct method to create a token is jwt.sign()
  2. Step 2: Match syntax with options

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

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

    Token creation method = sign() [OK]
Hint: Remember: jsonwebtoken uses sign() to create tokens [OK]
Common Mistakes:
  • Using incorrect method names like create or generate
  • Omitting the expiresIn option or using wrong syntax
3. Given the code snippet:
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 123 }, 'secret', { expiresIn: '2h' });
console.log(typeof token);

What will be the output when this code runs?
medium
A. 'object'
B. 'string'
C. 'undefined'
D. 'number'

Solution

  1. Step 1: Understand jwt.sign output type

    jwt.sign returns a JWT token as a string.
  2. Step 2: Check typeof token

    Using typeof on the token returns 'string'.
  3. Final Answer:

    'string' -> Option B
  4. Quick Check:

    jwt.sign() output type = string [OK]
Hint: jwt.sign() returns a token string, not an object [OK]
Common Mistakes:
  • Assuming the token is an object
  • Expecting undefined or number type
4. Identify the error in this JWT token creation code:
const jwt = require('jsonwebtoken');
const token = jwt.sign({ id: 1 }, 12345, { expiresIn: '1h' });
medium
A. Secret key should be a string, not a number
B. Payload must be a string, not an object
C. expiresIn option is invalid
D. jwt.sign requires a callback function

Solution

  1. Step 1: Check secret key type

    The secret key must be a string for signing the token securely.
  2. Step 2: Identify error in code

    The code uses 12345 (a number) as secret key, which is incorrect.
  3. Final Answer:

    Secret key should be a string, not a number -> Option A
  4. Quick Check:

    Secret key type = string [OK]
Hint: Secret key must always be a string for jwt.sign() [OK]
Common Mistakes:
  • Passing number instead of string as secret key
  • Thinking payload must be string
  • Believing expiresIn is invalid
  • Assuming callback is mandatory
5. You want to create a JWT token that expires in 30 minutes and includes the user's email and role. Which code snippet correctly achieves this in Express?
hard
A. jwt.sign({ email: user.email, role: user.role }, 'mySecret', { expiresIn: '30m' })
B. jwt.sign({ email: user.email, role: user.role }, 'mySecret', { expiresAt: '30m' })
C. jwt.sign({ email: user.email, role: user.role }, 'mySecret', { expireIn: 1800 })
D. jwt.sign({ email: user.email, role: user.role }, 'mySecret', { expiresIn: 30 })

Solution

  1. Step 1: Include correct payload fields

    The payload must include email and role from user object.
  2. Step 2: Use correct expiresIn format

    expiresIn accepts string like '30m' for 30 minutes; number means seconds but must be a number type without quotes.
  3. Step 3: Identify correct option

    Check each: expiresAt is invalid key; expireIn is misspelled; expiresIn: 30 is only 30 seconds. Only jwt.sign({ email: user.email, role: user.role }, 'mySecret', { expiresIn: '30m' }) is correct.
  4. Final Answer:

    jwt.sign({ email: user.email, role: user.role }, 'mySecret', { expiresIn: '30m' }) -> Option A
  5. Quick Check:

    expiresIn '30m' string format = correct [OK]
Hint: Use expiresIn with string like '30m' for minutes [OK]
Common Mistakes:
  • Using expiresAt instead of expiresIn
  • Using small numbers like 30 for expiresIn (30 seconds, not minutes)
  • Confusing expireIn with expiresIn