Consider this Express middleware that verifies a JWT token from the request header. What will happen if the token is missing?
import jwt from 'jsonwebtoken'; const verifyToken = (req, res, next) => { const token = req.headers['authorization']; if (!token) { return res.status(401).json({ message: 'No token provided' }); } jwt.verify(token, 'secretkey', (err, decoded) => { if (err) { return res.status(403).json({ message: 'Failed to authenticate token' }); } req.userId = decoded.id; next(); }); }; export default verifyToken;
Think about what happens when the token is not found in the headers.
If the token is missing, the middleware returns a 401 status and a message, stopping the request from continuing.
Choose the code snippet that correctly verifies a JWT token using the jsonwebtoken library in Express middleware.
Remember the order of parameters in the callback for jwt.verify.
The callback receives err first, then decoded. Option A uses the correct order and parameters.
Look at this middleware code. Why does it crash the server when an invalid token is sent?
import jwt from 'jsonwebtoken'; const verifyToken = (req, res, next) => { const token = req.headers['authorization']; const decoded = jwt.verify(token, 'secretkey'); req.userId = decoded.id; next(); }; export default verifyToken;
Think about what happens when jwt.verify fails without a try-catch.
jwt.verify throws an error if the token is invalid. Without a try-catch, this error crashes the server.
Given this middleware and a valid JWT token with payload { id: 42 }, what will req.userId be?
import jwt from 'jsonwebtoken'; const verifyToken = (req, res, next) => { const token = req.headers['authorization']; jwt.verify(token, 'secretkey', (err, decoded) => { if (err) { return res.status(403).json({ message: 'Invalid token' }); } req.userId = decoded.id; next(); }); }; export default verifyToken;
Check how the decoded token payload is assigned to req.userId.
The decoded token contains { id: 42 }, so req.userId is set to 42.
In Express middleware for JWT verification, why should next() be called only after the token is verified successfully?
Think about security and what happens if next() is called too early.
Calling next() only after verification ensures only authorized users access protected routes.