JWT token verification middleware checks if a user is allowed to access certain parts of a web app by confirming their token is valid.
JWT token verification middleware 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'); function verifyToken(req, res, next) { const authHeader = req.headers['authorization']; if (!authHeader) { return res.status(401).send('Access denied. No token provided.'); } const token = authHeader.split(' ')[1]; if (!token) { return res.status(401).send('Access denied. Token missing.'); } try { const decoded = jwt.verify(token, 'your-secret-key'); req.user = decoded; next(); } catch (err) { res.status(400).send('Invalid token.'); } }
The middleware reads the token from the Authorization header.
Use jwt.verify() to check if the token is valid and not expired.
Examples
Express
const authHeader = req.headers['authorization']; const token = authHeader.split(' ')[1];
Express
const decoded = jwt.verify(token, 'your-secret-key');next() to continue.Express
req.user = decoded; next();
Sample Program
This Express app has three routes:
- /public: anyone can access.
- /login: simulates login and returns a JWT token.
- /protected: only accessible if a valid JWT token is sent in the Authorization header.
The verifyToken middleware checks the token before allowing access to the protected route.
Express
const express = require('express'); const jwt = require('jsonwebtoken'); const app = express(); const PORT = 3000; const SECRET_KEY = 'mysecretkey'; // Middleware to verify JWT token function verifyToken(req, res, next) { const authHeader = req.headers['authorization']; if (!authHeader) { return res.status(401).send('Access denied. No token provided.'); } const token = authHeader.split(' ')[1]; // Expecting 'Bearer <token>' if (!token) { return res.status(401).send('Access denied. Token missing.'); } try { const decoded = jwt.verify(token, SECRET_KEY); req.user = decoded; next(); } catch (err) { res.status(400).send('Invalid token.'); } } // Public route app.get('/public', (req, res) => { res.send('This is a public route.'); }); // Protected route app.get('/protected', verifyToken, (req, res) => { res.send(`Welcome ${req.user.name}, you accessed a protected route!`); }); // Route to get a token (simulate login) app.get('/login', (req, res) => { // Normally, you'd check user credentials here const user = { id: 1, name: 'Alice' }; const token = jwt.sign(user, SECRET_KEY, { expiresIn: '1h' }); res.json({ token }); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
Important Notes
Always keep your secret key safe and never share it publicly.
The token is usually sent in the header as Authorization: Bearer <token>.
Use HTTPS to keep tokens secure during transmission.
Summary
JWT middleware checks if a token is valid before allowing access.
It protects routes by verifying user identity without sessions.
Tokens are sent in the Authorization header and verified with a secret key.
Practice
1. What is the main purpose of JWT token verification middleware in an Express app?
easy
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 AQuick 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
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 AQuick 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
Solution
Step 1: Check token verification flow
If token is invalid, jwt.verify throws an error caught by catch block.Step 2: Observe catch block response
Catch block sends status 400 with message 'Invalid token'.Final Answer:
The middleware sends a 400 status with 'Invalid token' message -> Option DQuick 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
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 BQuick 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
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 CQuick 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
