Script Valley
Express.js: APIs and Middleware
Authentication and AuthorizationLesson 4.3

Role-based access control (RBAC) middleware in Express

RBAC pattern, role middleware factory, req.user.role, 403 Forbidden, authorize function, multiple roles, middleware chaining with auth, resource ownership

Role-Based Access Control Middleware

RBAC restricts access based on the user's role. Build an authorize middleware factory that accepts allowed roles and returns a middleware function.

authorize middleware factory

function authorize(...roles) {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({ error: 'Not authenticated' });
    }

    if (!roles.includes(req.user.role)) {
      return res.status(403).json({
        error: `Access denied. Required roles: ${roles.join(', ')}`
      });
    }

    next();
  };
}

module.exports = authorize;

Applying RBAC to routes

const authenticate = require('./middleware/authenticate');
const authorize = require('./middleware/authorize');

// Only admins
app.delete('/users/:id', authenticate, authorize('admin'), deleteUser);

// Admins and managers
app.get('/reports', authenticate, authorize('admin', 'manager'), getReports);

// Any authenticated user
app.get('/profile', authenticate, getProfile);

Resource ownership check

function ownerOrAdmin(req, res, next) {
  const isOwner = req.user.userId === parseInt(req.params.id);
  const isAdmin = req.user.role === 'admin';
  if (!isOwner && !isAdmin) {
    return res.status(403).json({ error: 'Access denied' });
  }
  next();
}

Always run authenticate before authorize โ€” authorization requires a verified identity.

Up next

How to hash passwords and store them securely with bcrypt

Sign in to track progress

Role-based access control (RBAC) middleware in Express โ€” Authentication and Authorization โ€” Express.js: APIs and Middleware โ€” Script Valley โ€” Script Valley