Production Express Auth Middleware
This middleware extracts the token from the `Authorization: Bearer <token>` header, verifies the signature against `process.env.JWT_SECRET`, checks token expiration, and attaches the decoded user payload to `req.user`.
javascriptHardened Express.js JWT verification middleware
const jwt = require('jsonwebtoken');
function requireAuth(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing or malformed Authorization header' });
}
const token = authHeader.split(' ')[1];
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET, {
algorithms: ['HS256'],
});
req.user = decoded;
next();
} catch (err) {
if (err.name === 'TokenExpiredError') {
return res.status(401).json({ error: 'Token has expired', code: 'TOKEN_EXPIRED' });
}
return res.status(401).json({ error: 'Invalid authentication token' });
}
}Generate in Browser
Launch GeneratorNeed a cryptographically secure JWT secret right now?
Generate 128 to 512-bit keys in Hex or Base64 using Web Crypto with zero server transmission.
Frequently Asked Questions
Can I store the JWT in an HttpOnly cookie instead of Bearer header?
Yes, HttpOnly SameSite=Strict cookies protect tokens from cross-site scripting (XSS) attacks in single-page applications.
Related Technical Guides
Implementation
Setting JWT_SECRET in Node.js: Production Security, dotenv, and Docker
How to configure JWT_SECRET in Node.js using dotenv, environment validation, Docker secrets, and secret managers. Complete code examples.
ImplementationTop 7 Critical JWT Authentication Mistakes Developers Make in Production
Avoid disastrous security flaws: "alg": "none", weak secrets, missing expiration, storing tokens in localStorage, and trusting client payloads.