Q20: How do you implement JWT Authentication middleware in Express?
JSON Web Tokens (JWT) enable stateless authentication across REST endpoints. Authentication middleware verifies tokens passed in the Authorization request header.
JWT Guard Middleware
const jwt = require('jsonwebtoken');
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1]; // Extract Bearer TOKEN
if (!token) return res.status(401).json({ error: 'Access token missing' });
jwt.verify(token, process.env.JWT_SECRET, (err, decodedUser) => {
if (err) return res.status(403).json({ error: 'Invalid or expired token' });
req.user = decodedUser; // Attach user payload to request
next();
});
};
app.get('/api/protected', authenticateToken, (req, res) => {
res.json({ message: 'Secure data', user: req.user });
});💡 The middleware extracts, decodes, and attaches the payload user object to req before proceeding.
Key Takeaways
- Return 401 Unauthorized if the token is missing; return 403 Forbidden if the token is invalid.
- Attach decoded user details onto
req.userto make them accessible to downstream route handlers.