Complete the code to import the JWT library.
const jwt = require('[1]');
The jsonwebtoken package is used to work with JWT tokens in Express.
Complete the code to extract the token from the Authorization header.
const token = req.headers.authorization && req.headers.authorization.split(' ')[[1]];
The Authorization header usually has the format 'Bearer <token>'. Splitting by space, the token is at index 1.
Fix the error in the token verification call.
jwt.verify(token, process.env.JWT_SECRET, ([1], decoded) => { if (error) { return res.status(401).json({ message: 'Unauthorized' }); } req.user = decoded; next(); });
The callback function parameter for errors is commonly named error here to match the usage inside the function.
Fill both blanks to create the middleware function and export it.
function [1](req, res, next) { // middleware code here } module.exports = [2];
The function is named verifyToken and exported with the same name for clarity and usage.
Fill all three blanks to complete the middleware that verifies the JWT token and handles errors.
function verifyToken(req, res, next) {
const token = req.headers.authorization && req.headers.authorization.split(' ')[[1]];
if (!token) {
return res.status(401).json({ message: '[2]' });
}
jwt.verify(token, process.env.JWT_SECRET, (error, decoded) => {
if (error) {
return res.status(401).json({ message: '[3]' });
}
req.user = decoded;
next();
});
}The token is at index 1 after splitting the Authorization header. The error messages clearly indicate missing or invalid tokens.