Bird
Raised Fist0
Expressframework~10 mins

JWT token verification middleware 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 verification middleware
Incoming HTTP Request
Check for Authorization Header
Yes / No
Extract JWT
Verify JWT Signature
Attach User Info
Call Next Middleware/Route Handler
The middleware checks the request for a JWT token, verifies it, and either attaches user info and continues or rejects the request.
Execution Sample
Express
function verifyToken(req, res, next) {
  const token = req.headers['authorization']?.split(' ')[1];
  if (!token) return res.status(401).send('No token');
  jwt.verify(token, secret, (err, user) => {
    if (err) return res.status(401).send('Invalid token');
    req.user = user;
    next();
  });
}
This middleware extracts a JWT from the Authorization header, verifies it, and either rejects or passes control with user info.
Execution Table
StepActionToken ExtractedVerification ResultRequest User AttachedResponse SentNext Called
1Check Authorization headerBearer abc.def.ghiN/ANoNoNo
2Extract token from headerabc.def.ghiN/ANoNoNo
3Verify token signatureabc.def.ghiValidNoNoNo
4Attach user info to reqabc.def.ghiValidYesNoNo
5Call next middlewareabc.def.ghiValidYesNoYes
6Request proceeds to next handlerabc.def.ghiValidYesNoYes
💡 Middleware ends after calling next() if token is valid; otherwise, sends 401 response.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
req.headers['authorization']Bearer abc.def.ghiBearer abc.def.ghiBearer abc.def.ghiBearer abc.def.ghiBearer abc.def.ghiBearer abc.def.ghi
tokenundefinedundefinedabc.def.ghiabc.def.ghiabc.def.ghiabc.def.ghi
verification error (err)undefinedundefinedundefinednullnullnull
user (decoded token)undefinedundefinedundefined{id:123}{id:123}{id:123}
req.userundefinedundefinedundefinedundefined{id:123}{id:123}
Key Moments - 3 Insights
Why does the middleware send a 401 response if the token is missing?
Because if no token is extracted, the middleware immediately sends a 401 response to reject unauthorized access.
What happens if the token verification fails?
If verification returns an error, the middleware sends a 401 response and does not call next(), stopping further processing.
How does the middleware pass user info to later handlers?
In step 4, the middleware attaches the decoded user info to req.user, so subsequent middleware or routes can access it.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'token' after Step 2?
Aundefined
B"Bearer abc.def.ghi"
C"abc.def.ghi"
Dnull
💡 Hint
Check the 'Token Extracted' column in row for Step 2.
At which step does the middleware attach user info to the request object?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Request User Attached' column in execution_table.
If the token is invalid, what will the middleware do according to the execution flow?
AAttach user info and call next()
BSend 401 Unauthorized response
CIgnore and call next()
DSend 200 OK response
💡 Hint
Refer to the concept_flow and execution_table step 3 for invalid verification.
Concept Snapshot
JWT Verification Middleware in Express:
- Extract token from Authorization header
- If missing, send 401 Unauthorized
- Verify token signature with secret
- If invalid, send 401 Unauthorized
- If valid, attach decoded user info to req.user
- Call next() to continue processing
Full Transcript
This middleware runs on each incoming HTTP request. It first looks for the Authorization header. If the header is missing or does not contain a token, it immediately sends a 401 Unauthorized response. If a token is found, it verifies the token's signature using a secret key. If verification fails, it sends a 401 Unauthorized response. If verification succeeds, it attaches the decoded user information to the request object as req.user. Finally, it calls next() to pass control to the next middleware or route handler. This ensures only requests with valid tokens proceed.

Practice

(1/5)
1. What is the main purpose of JWT token verification middleware in an Express app?
easy
A. To check if the incoming request has a valid JWT token before allowing access
B. To store user sessions on the server
C. To encrypt the user's password before saving
D. To serve static files like images and CSS

Solution

  1. Step 1: Understand JWT middleware role

    JWT middleware checks the token sent by the client to confirm identity.
  2. Step 2: Compare options with JWT purpose

    Only "To check if the incoming request has a valid JWT token before allowing access" describes verifying a token before access, which is the middleware's job.
  3. Final Answer:

    To check if the incoming request has a valid JWT token before allowing access -> Option A
  4. Quick Check:

    JWT middleware verifies token [OK]
Hint: JWT middleware always verifies token validity before access [OK]
Common Mistakes:
  • Confusing JWT with session storage
  • Thinking JWT middleware encrypts passwords
  • Assuming middleware serves static files
2. Which of the following is the correct way to extract the JWT token from the Authorization header in Express middleware?
easy
A. const token = req.headers.authorization.split(' ')[1];
B. const token = req.body.token;
C. const token = req.query.token;
D. const token = req.cookies.token;

Solution

  1. Step 1: Identify standard JWT token location

    JWT tokens are usually sent in the Authorization header as 'Bearer token'.
  2. Step 2: Extract token correctly

    Splitting the header string by space and taking the second part gets the token.
  3. Final Answer:

    const token = req.headers.authorization.split(' ')[1]; -> Option A
  4. Quick Check:

    Authorization header split [OK]
Hint: JWT token is after 'Bearer ' in Authorization header [OK]
Common Mistakes:
  • Trying to get token from body or query instead of header
  • Not splitting the header string
  • Assuming token is in cookies by default
3. Given this Express JWT middleware snippet, what happens if the token is invalid?
const jwt = require('jsonwebtoken');
function verifyToken(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).send('Access denied');
  try {
    const verified = jwt.verify(token, 'secretkey');
    req.user = verified;
    next();
  } catch (err) {
    res.status(400).send('Invalid token');
  }
}
medium
A. The middleware calls next() and allows access
B. The middleware crashes with an unhandled exception
C. The middleware sends a 401 status with 'Access denied' message
D. The middleware sends a 400 status with 'Invalid token' message

Solution

  1. Step 1: Check token verification flow

    If token is invalid, jwt.verify throws an error caught by catch block.
  2. Step 2: Observe catch block response

    Catch block sends status 400 with message 'Invalid token'.
  3. Final Answer:

    The middleware sends a 400 status with 'Invalid token' message -> Option D
  4. Quick Check:

    Invalid token triggers 400 response [OK]
Hint: Invalid token triggers catch block sending 400 error [OK]
Common Mistakes:
  • Confusing 401 and 400 status codes
  • Assuming next() is called on invalid token
  • Thinking middleware crashes on invalid token
4. Identify the error in this JWT verification middleware code:
const jwt = require('jsonwebtoken');
function verifyToken(req, res, next) {
  const token = req.headers.authorization.split(' ')[1];
  if (!token) res.status(401).send('Access denied');
  try {
    const verified = jwt.verify(token, 'secretkey');
    req.user = verified;
    next();
  } catch (err) {
    res.status(400).send('Invalid token');
  }
}
medium
A. jwt.verify is called with wrong secret key
B. Missing return after sending 401 response causes jwt.verify to run anyway
C. Token is extracted incorrectly from headers
D. next() is called inside catch block instead of try block

Solution

  1. Step 1: Check handling when token is missing

    If token is missing, res.status(401).send() is called but no return statement stops execution.
  2. Step 2: Understand consequence of missing return

    Without return, code continues and jwt.verify runs with undefined token, causing errors or unexpected behavior.
  3. Final Answer:

    Missing return after sending 401 response causes jwt.verify to run anyway -> Option B
  4. Quick Check:

    Return needed after 401 response [OK]
Hint: Always return after sending response to stop middleware [OK]
Common Mistakes:
  • Forgetting to return after res.send()
  • Assuming jwt.verify secret is wrong here
  • Misreading token extraction line
5. You want to protect multiple routes with JWT verification but also allow public access to some routes. Which is the best way to apply JWT middleware in Express?
hard
A. Apply JWT middleware after route handlers to catch errors
B. Apply JWT middleware globally to all routes and skip it conditionally inside middleware
C. Apply JWT middleware only to protected routes using router.use or route-specific middleware
D. Apply JWT middleware only once in app.listen callback

Solution

  1. Step 1: Understand middleware scope

    Applying middleware globally affects all routes, including public ones, which is not ideal.
  2. Step 2: Use route-specific middleware for protection

    Applying JWT middleware only on protected routes keeps public routes accessible without token.
  3. Final Answer:

    Apply JWT middleware only to protected routes using router.use or route-specific middleware -> Option C
  4. Quick Check:

    Protect routes selectively with middleware [OK]
Hint: Use middleware only on routes needing protection [OK]
Common Mistakes:
  • Applying middleware globally and skipping inside code
  • Applying middleware after route handlers
  • Trying to apply middleware in app.listen