0
0
Expressframework~20 mins

JWT token creation in Express - Practice Problems & Coding Challenges

Choose your learning style9 modes available
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.