Concept Flow - Role-based access control
User sends request
Middleware checks user role
Allow access
Next handler
The request passes through middleware that checks the user's role. If the role matches, access is allowed; otherwise, access is denied.
function checkRole(role) {
return (req, res, next) => {
if (req.user?.role === role) next();
else res.status(403).send('Forbidden');
};
}| Step | Request user.role | Condition (req.user?.role === role) | Action | Response |
|---|---|---|---|---|
| 1 | 'admin' | admin === admin | next() called | Request proceeds |
| 2 | 'user' | user === admin | res.status(403).send('Forbidden') | 403 Forbidden sent |
| 3 | undefined | undefined === admin | res.status(403).send('Forbidden') | 403 Forbidden sent |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 |
|---|---|---|---|---|
| req.user.role | undefined | admin | user | undefined |
| role (required) | admin | admin | admin | admin |
| Condition result | N/A | true | false | false |
Role-based access control in Express uses middleware to check user roles. Middleware compares req.user.role with required role. If roles match, call next() to continue. If not, send 403 Forbidden response. Use optional chaining to avoid errors if req.user is missing.