Express.js Role Access Control

Role access control decides what each logged-in user may do. Authentication answers the question of who the user is. Authorization answers the question of what that user may do. A shop app lets customers view products, lets staff edit products, and lets admins delete accounts. Roles organize those permissions into simple labels.

The Office Badge Analogy

An office gives every worker a badge. A visitor badge opens the lobby. An employee badge opens the lobby and the work floor. A manager badge opens the lobby, the work floor, and the records room. The door reader checks the badge color, not the person. Role checks in Express work the same way.

Role Permission Table

Actionusereditoradmin
View articlesYesYesYes
Edit articlesNoYesYes
Delete usersNoNoYes

Access Flow Diagram

Request with token
       |
       v
authenticate middleware
  (who is this user?)
       |
       v
authorize middleware
  (is the role allowed?)
       |
   Yes |        No
       v         v
  Controller    403 Forbidden

Store the Role

Each user record carries a role field. A default value of user keeps new accounts safe.

const userSchema = new mongoose.Schema({
  email:    { type: String, required: true, unique: true },
  password: { type: String, required: true },
  role:     {
    type: String,
    enum: ['user', 'editor', 'admin'],
    default: 'user'
  }
});

Authenticate and Attach the User

The first middleware reads the token and places the user on the request object. The example uses a JSON Web Token that holds the user id and the role.

const jwt = require('jsonwebtoken');

function authenticate(req, res, next) {
  const header = req.headers.authorization || '';
  const token = header.replace('Bearer ', '');

  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch (err) {
    res.status(401).json({ error: 'Login required' });
  }
}

Authorize by Role

The second middleware accepts a list of allowed roles and returns a checking function. Status 403 means the user is known but lacks permission.

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

Protect Routes

Place the two middleware functions before the controller. The order matters because authorize needs the user that authenticate attached.

app.get('/articles', authenticate, (req, res) => {
  res.json({ articles: [] });
});

app.put('/articles/:id', authenticate, authorize('editor', 'admin'), (req, res) => {
  res.json({ message: 'Article updated' });
});

app.delete('/users/:id', authenticate, authorize('admin'), (req, res) => {
  res.json({ message: 'User deleted' });
});

Status Codes to Remember

  • 401 Unauthorized: the user is not logged in or the token is bad.
  • 403 Forbidden: the user is logged in but lacks the role.

Check Ownership

Roles alone sometimes fall short. A regular user may edit only their own profile. Add an ownership check inside the controller.

app.put('/profile/:id', authenticate, (req, res) => {
  const isOwner = req.user.id === req.params.id;
  const isAdmin = req.user.role === 'admin';

  if (!isOwner && !isAdmin) {
    return res.status(403).json({ error: 'Access denied' });
  }
  res.json({ message: 'Profile updated' });
});

Best Practices

  • Grant the lowest role that still lets the user do the job.
  • Check roles on the server. Hidden buttons in the frontend offer no protection.
  • Keep role names in one shared constants file.
  • Never let a user set their own role through a sign-up form.
  • Log every denied attempt on sensitive routes.

Small apps manage well with three roles. Large apps move toward permission lists, where each role holds a set of named actions. The same two-step flow of authenticate and authorize still applies.

Real-World Scenario

A school portal serves students, teachers, and principals. Students read grades. Teachers enter grades. Principals manage teacher accounts. One authorize middleware protects every route, and the role in the token decides the outcome. Adding a fourth role, such as librarian, needs one new enum value and a few updated route lists.