JWT tokens help keep users logged in safely. They store user info in a secure way so the server can check who you are without asking every time.
JWT token creation in Express
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Express
const jwt = require('jsonwebtoken');
const token = jwt.sign(payload, secretKey, options);payload is the user data you want to include in the token.
secretKey is a secret string only your server knows to sign the token.
Examples
Express
const token = jwt.sign({ userId: 123 }, 'mySecretKey');Express
const token = jwt.sign({ userId: 123 }, 'mySecretKey', { expiresIn: '1h' });Express
const token = jwt.sign({ userId: 123, role: 'admin' }, 'mySecretKey', { algorithm: 'HS256' });Sample Program
This Express server has a /login route. When you send a username in JSON, it creates a JWT token with that username and sends it back. The token expires in 2 hours.
Express
import express from 'express'; import jwt from 'jsonwebtoken'; const app = express(); app.use(express.json()); const SECRET_KEY = 'superSecret123'; app.post('/login', (req, res) => { const { username } = req.body; if (!username) { return res.status(400).json({ error: 'Username required' }); } // Create a token with username and expiry of 2 hours const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: '2h' }); res.json({ token }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Important Notes
Always keep your secret key safe and never share it publicly.
Tokens can include expiration to improve security.
Use HTTPS to protect tokens during network transfer.
Summary
JWT tokens store user info safely for authentication.
Use jwt.sign() with a payload and secret key to create tokens.
Set token expiration to limit how long tokens are valid.
Practice
1. What is the main purpose of creating a JWT token in an Express app?
easy
Solution
Step 1: Understand JWT token role
JWT tokens are used to safely store user data for verifying identity.Step 2: Identify correct purpose
Among the options, only storing user info for authentication matches JWT's role.Final Answer:
To securely store user information for authentication -> Option DQuick 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
Solution
Step 1: Recall jsonwebtoken method
The correct method to create a token is jwt.sign()Step 2: Match syntax with options
Only jwt.sign(payload, secretKey, { expiresIn: '1h' }) uses jwt.sign() with payload, secretKey, and expiresIn correctly.Final Answer:
jwt.sign(payload, secretKey, { expiresIn: '1h' }) -> Option CQuick 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:
What will be the output when this code runs?
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
Solution
Step 1: Understand jwt.sign output type
jwt.sign returns a JWT token as a string.Step 2: Check typeof token
Using typeof on the token returns 'string'.Final Answer:
'string' -> Option BQuick 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
Solution
Step 1: Check secret key type
The secret key must be a string for signing the token securely.Step 2: Identify error in code
The code uses 12345 (a number) as secret key, which is incorrect.Final Answer:
Secret key should be a string, not a number -> Option AQuick 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
Solution
Step 1: Include correct payload fields
The payload must include email and role from user object.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.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.Final Answer:
jwt.sign({ email: user.email, role: user.role }, 'mySecret', { expiresIn: '30m' }) -> Option AQuick 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
