Complete the code to import the JWT library.
const jwt = require('[1]');
The jsonwebtoken package is used to generate and verify JWT tokens in Node.js.
Complete the code to generate a JWT token with a secret key.
const token = jwt.sign({ userId: 123 }, '[1]');The secret key is a string used to sign the token securely. Here, 'mySecretKey' is used as an example.
Fix the error in the code to verify a JWT token using the secret key.
const decoded = jwt.verify(token, '[1]');
The jwt.verify function requires the same secret key used to sign the token to decode it correctly.
Fill both blanks to generate a token with an expiration time of 1 hour.
const token = jwt.sign({ id: user.id }, '[1]', { expiresIn: '[2]' });The secret key is needed to sign the token, and the expiresIn option sets the token to expire in 1 hour using '1h'.
Fill all three blanks to decode a token safely with error handling.
try { const decoded = jwt.[1](token, '[2]'); console.log(decoded.[3]); } catch (err) { console.error('Invalid token'); }
Use verify to decode the token with the secret key 'mySecretKey'. Then access the userId property from the decoded token.