Roadmap › Node.js — Runtime Internals, Express, APIs and SQL Server › Module: Building APIs
Lessons in this course (11)
9. Authentication with JWT, configuration and security
Intermediate★ Must knowLesson 9 of 11
js
import jwt from 'jsonwebtoken';
export function requireAuth(req, res, next) {
const header = req.headers.authorization ?? '';
const token = header.startsWith('Bearer ') ? header.slice(7) : null;
if (!token) return res.status(401).json({ title: 'Missing token' });
try {
req.user = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'], audience: 'shop-api' });
next();
} catch {
res.status(401).json({ title: 'Invalid token' });
}
}
export const requireRole = (role) => (req, res, next) => (req.user?.roles?.includes(role) ? next() : res.status(403).json({ title: 'Forbidden' }));
router.delete('/:id', requireAuth, requireRole('Admin'), controller.remove);Security checklist: helmet (headers), CORS allow-list, input validation (zod), parameterised SQL, rate limiting (express-rate-limit), hash passwords with bcrypt/argon2, secrets in environment variables/Key Vault, npm audit and Dependabot, avoid eval/dynamic require of user input, limit body size, don't leak stack traces, keep Node on a supported LTS.