0
0
Expressframework~10 mins

JWT token verification middleware in Express - Step-by-Step Execution

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