Bird
Raised Fist0
Expressframework~10 mins

JWT token creation in Express - Step-by-Step Execution

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
Concept Flow - JWT token creation
Receive user data
Prepare payload
Use secret key
Call jwt.sign()
Generate token string
Send token to user
This flow shows how user data is turned into a JWT token using a secret key and the jwt.sign() function.
Execution Sample
Express
const jwt = require('jsonwebtoken');

const payload = { id: 123, name: 'Alice' };
const secret = 'mysecretkey';

const token = jwt.sign(payload, secret);
console.log(token);
This code creates a JWT token from user data and a secret key, then prints the token string.
Execution Table
StepActionInputOutputNotes
1Prepare payload{ id: 123, name: 'Alice' }Payload object readyUser data collected
2Set secret key'mysecretkey'Secret key string readyUsed to sign token
3Call jwt.sign()payload, secretJWT token string generatedToken encodes payload and signature
4Print tokentoken stringToken string output to consoleToken looks like three base64 parts
5EndN/AProcess completeToken ready to send to user
💡 Token creation completes after jwt.sign() returns the token string
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
payloadundefined{ id: 123, name: 'Alice' }{ id: 123, name: 'Alice' }{ id: 123, name: 'Alice' }{ id: 123, name: 'Alice' }
secretundefinedundefined'mysecretkey''mysecretkey''mysecretkey'
tokenundefinedundefinedundefinedeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Key Moments - 3 Insights
Why do we need a secret key when creating a JWT token?
The secret key is used to sign the token so that the server can verify it later. Without it, anyone could create fake tokens. See step 2 and 3 in the execution_table.
What does the jwt.sign() function output?
It outputs a string token that contains encoded user data and a signature. This token is what we send to the user. See step 3 and 4 in the execution_table.
Is the payload data visible in the token?
Yes, the payload is encoded (not encrypted) inside the token, so anyone can decode it but cannot change it without the secret. See step 3 output.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'token' after step 3?
AA JWT token string
BThe secret key string
CThe payload object
DUndefined
💡 Hint
Check the 'Output' column at step 3 in the execution_table.
At which step is the secret key set in the variable_tracker?
AAfter Step 1
BAfter Step 2
CAfter Step 3
DFinal
💡 Hint
Look at the 'secret' row in variable_tracker and see when it changes from undefined.
If we change the secret key, what will happen to the token?
AThe token will stay the same
BThe payload will change
CThe token will be different because the signature changes
DThe token will be invalid immediately
💡 Hint
Think about how the secret key affects the signature in jwt.sign() at step 3.
Concept Snapshot
JWT token creation in Express:
- Prepare a payload object with user data
- Use a secret key string
- Call jwt.sign(payload, secret) to create token
- Token is a string encoding data + signature
- Send token to user for authentication
Full Transcript
This visual trace shows how to create a JWT token in Express. First, user data is prepared as a payload object. Then a secret key string is set. The jwt.sign() function is called with the payload and secret, which returns a token string. This token contains encoded user data and a signature to verify authenticity. Finally, the token is printed or sent to the user. Variables like payload, secret, and token change step-by-step as shown. Key points include the importance of the secret key for signing and the token being a string output. This process is essential for secure user authentication in web apps.

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