Script Valley
Node.js: The Complete Runtime
Authentication and SecurityLesson 5.2

Building a JWT auth middleware for Express

Bearer token extraction, auth middleware, protect route, role-based access control, attaching user to req, optional auth, public vs protected routes

Extracting the Token from Headers

The client sends the JWT in the Authorization: Bearer token header. The middleware extracts it, verifies it, and attaches the decoded payload to req.user.

const jwt = require('jsonwebtoken');

function authenticate(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'No token provided' });
  }

  const token = authHeader.split(' ')[1];
  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch (err) {
    const msg = err.name === 'TokenExpiredError' ? 'Token expired' : 'Invalid token';
    res.status(401).json({ error: msg });
  }
}

app.get('/api/profile', authenticate, (req, res) => {
  res.json({ userId: req.user.userId });
});

Role-Based Access Control

function authorize(...roles) {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({ error: 'Forbidden' });
    }
    next();
  };
}

app.delete('/api/users/:id', authenticate, authorize('admin'), handler);

Up next

Password hashing and secure login in Node.js

Sign in to track progress

Building a JWT auth middleware for Express โ€” Authentication and Security โ€” Node.js: The Complete Runtime โ€” Script Valley โ€” Script Valley