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
JWT Token Verification Middleware in Express
📖 Scenario: You are building a simple Express server that needs to protect certain routes by verifying JWT tokens sent by clients.This helps ensure only users with valid tokens can access protected data.
🎯 Goal: Create a JWT verification middleware function in Express that checks the token from the request headers and allows or denies access accordingly.
📋 What You'll Learn
Create a variable called jwt that requires the jsonwebtoken package
Create a middleware function called verifyToken that reads the token from req.headers['authorization']
Check if the token exists and starts with 'Bearer '
Verify the token using jwt.verify with the secret key 'mysecretkey'
If verification passes, call next() to continue; otherwise, respond with status 401 and message 'Unauthorized'
Export the verifyToken middleware function
💡 Why This Matters
🌍 Real World
JWT token verification middleware is used in real web servers to protect routes and ensure only authenticated users can access certain resources.
💼 Career
Understanding how to implement middleware for JWT verification is a common requirement for backend developers working with Node.js and Express in secure web applications.
Progress0 / 4 steps
1
Setup JWT package import
Create a variable called jwt that requires the jsonwebtoken package.
Express
Hint
Use require('jsonwebtoken') to import the JWT library.
2
Create the verifyToken middleware function
Create a middleware function called verifyToken that reads the token from req.headers['authorization'] and stores it in a variable called authHeader.
Express
Hint
Middleware functions take req, res, and next as parameters.
Read the token from req.headers['authorization'].
3
Check token presence and verify it
Inside verifyToken, check if authHeader exists and starts with 'Bearer '. Extract the token part after 'Bearer ' into a variable called token. Then verify the token using jwt.verify(token, 'mysecretkey', callback). If verification fails, respond with status 401 and message 'Unauthorized'. If it passes, call next().
Express
Hint
Check if authHeader exists and starts with 'Bearer '.
Use slice(7) to get the token part.
Use jwt.verify with a callback to handle success or failure.
4
Export the verifyToken middleware
Export the verifyToken middleware function using module.exports = verifyToken;.
Express
Hint
Use module.exports to export the middleware function.
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
Step 1: Understand JWT middleware role
JWT middleware checks the token sent by the client to confirm identity.
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.
Final Answer:
To check if the incoming request has a valid JWT token before allowing access -> Option A
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
Step 1: Identify standard JWT token location
JWT tokens are usually sent in the Authorization header as 'Bearer token'.
Step 2: Extract token correctly
Splitting the header string by space and taking the second part gets the token.
Final Answer:
const token = req.headers.authorization.split(' ')[1]; -> Option A
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?
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
Step 1: Check handling when token is missing
If token is missing, res.status(401).send() is called but no return statement stops execution.
Step 2: Understand consequence of missing return
Without return, code continues and jwt.verify runs with undefined token, causing errors or unexpected behavior.
Final Answer:
Missing return after sending 401 response causes jwt.verify to run anyway -> Option B
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
Step 1: Understand middleware scope
Applying middleware globally affects all routes, including public ones, which is not ideal.
Step 2: Use route-specific middleware for protection
Applying JWT middleware only on protected routes keeps public routes accessible without token.
Final Answer:
Apply JWT middleware only to protected routes using router.use or route-specific middleware -> Option C
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