Bird
Raised Fist0
Expressframework~10 mins

Role-based access control in Express - Step-by-Step Execution

Choose your learning style10 modes available
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.
Execution Sample
Express
function checkRole(role) {
  return (req, res, next) => {
    if (req.user?.role === role) next();
    else res.status(403).send('Forbidden');
  };
}
This middleware checks if the logged-in user's role matches the required role and either allows the request to continue or denies access.
Execution Table
StepRequest user.roleCondition (req.user?.role === role)ActionResponse
1'admin'admin === adminnext() calledRequest proceeds
2'user'user === adminres.status(403).send('Forbidden')403 Forbidden sent
3undefinedundefined === adminres.status(403).send('Forbidden')403 Forbidden sent
💡 Access denied when user role does not match or is missing; allowed only when roles match.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
req.user.roleundefinedadminuserundefined
role (required)adminadminadminadmin
Condition resultN/Atruefalsefalse
Key Moments - 2 Insights
Why does the middleware deny access when req.user is undefined?
Because the condition req.user?.role === role evaluates to false when req.user is undefined, as shown in execution_table step 3, so access is denied.
What happens if the user's role matches the required role?
The middleware calls next(), allowing the request to continue, as shown in execution_table step 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the response when req.user.role is 'user' and required role is 'admin'?
A403 Forbidden sent
B500 Internal Server Error
CRequest proceeds
DRedirect to login
💡 Hint
Check execution_table row 2 under 'Response' column.
At which step does the condition req.user?.role === role evaluate to true?
AStep 3
BStep 2
CStep 1
DNone
💡 Hint
Look at execution_table 'Condition' column for each step.
If the middleware allowed access when req.user is undefined, what would change in the execution table?
AStep 2 response would be 200 OK
BStep 3 action would be next() called
CStep 1 condition would be false
DNo changes
💡 Hint
Focus on Step 3 'Action' and 'Response' columns in execution_table.
Concept Snapshot
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.
Full Transcript
Role-based access control in Express works by using middleware functions that check the user's role before allowing access to certain routes. When a request comes in, the middleware looks at req.user.role and compares it to the required role. If they match, the middleware calls next() to let the request continue. If they don't match or if req.user is missing, the middleware sends a 403 Forbidden response to deny access. This prevents unauthorized users from accessing protected parts of the app. The execution table shows three cases: when the user is an admin (access allowed), when the user is a regular user (access denied), and when no user is logged in (access denied). Understanding this flow helps keep your app secure by controlling who can do what.

Practice

(1/5)
1. What is the main purpose of role-based access control (RBAC) in an Express app?
easy
A. To speed up the server response time
B. To limit user actions based on their assigned roles
C. To store user passwords securely
D. To log all user activities automatically

Solution

  1. Step 1: Understand RBAC concept

    RBAC means controlling what users can do depending on their role, like admin or guest.
  2. Step 2: Identify main purpose in Express

    In Express, RBAC limits access to routes or actions based on user roles to keep the app safe.
  3. Final Answer:

    To limit user actions based on their assigned roles -> Option B
  4. Quick Check:

    RBAC controls user permissions = A [OK]
Hint: RBAC controls what users can do by role [OK]
Common Mistakes:
  • Confusing RBAC with performance optimization
  • Thinking RBAC stores passwords
  • Assuming RBAC logs activities automatically
2. Which of the following is the correct way to define a middleware function in Express to check if a user has the role 'admin'?
easy
A. function checkAdmin(req, res, next) { if(req.user.role === 'admin') next(); else res.status(403).send('Forbidden'); }
B. function checkAdmin(req, res) { if(req.user.role == 'admin') next(); else res.send('Forbidden'); }
C. function checkAdmin(req, res, next) { if(req.user.role = 'admin') next(); else res.status(403).send('Forbidden'); }
D. function checkAdmin(req, res, next) { if(req.user.role !== 'admin') next(); else res.status(403).send('Forbidden'); }

Solution

  1. Step 1: Check middleware signature

    Middleware must have three parameters: req, res, next.
  2. Step 2: Verify role check and response

    function checkAdmin(req, res, next) { if(req.user.role === 'admin') next(); else res.status(403).send('Forbidden'); } correctly compares role with 'admin' using === and calls next() if true; else sends 403 status.
  3. Final Answer:

    function checkAdmin(req, res, next) { if(req.user.role === 'admin') next(); else res.status(403).send('Forbidden'); } -> Option A
  4. Quick Check:

    Middleware with correct params and strict role check = D [OK]
Hint: Middleware needs (req, res, next) and strict role check [OK]
Common Mistakes:
  • Using assignment (=) instead of comparison (===)
  • Missing next() parameter or call
  • Wrong logic reversing role check
3. Given this Express route with role check middleware, what will be the response if a user with role 'user' tries to access it?
app.get('/admin', checkAdmin, (req, res) => { res.send('Welcome Admin'); });
function checkAdmin(req, res, next) {
if(req.user.role === 'admin') next();
else res.status(403).send('Forbidden');
}
medium
A. 403 Forbidden status with 'Forbidden' message
B. 'Welcome Admin'
C. 500 Internal Server Error
D. 404 Not Found

Solution

  1. Step 1: Analyze middleware behavior for role 'user'

    The middleware checks if role is 'admin'. Since role is 'user', condition fails.
  2. Step 2: Determine response when role check fails

    Middleware sends 403 status with 'Forbidden' message and does not call next(), so route handler is skipped.
  3. Final Answer:

    403 Forbidden status with 'Forbidden' message -> Option A
  4. Quick Check:

    Non-admin blocked with 403 Forbidden = B [OK]
Hint: Middleware blocks non-admin with 403, no next() call [OK]
Common Mistakes:
  • Assuming route handler runs for non-admin
  • Confusing 403 with 404 or 500 errors
  • Ignoring middleware role check logic
4. Identify the error in this Express middleware for role-based access control:
function checkRole(req, res, next) {
if(req.user.role = 'admin') {
next();
} else {
res.status(403).send('Access denied');
}
}
medium
A. Middleware missing req and res parameters
B. Missing next() call inside the else block
C. Incorrect status code for access denial
D. Using assignment (=) instead of comparison (===) in the if condition

Solution

  1. Step 1: Check the if condition syntax

    The condition uses single = which assigns 'admin' to req.user.role instead of comparing it.
  2. Step 2: Understand impact of assignment in condition

    Assignment always returns truthy, so else block never runs, causing wrong behavior.
  3. Final Answer:

    Using assignment (=) instead of comparison (===) in the if condition -> Option D
  4. Quick Check:

    Use === for comparison, not = [OK]
Hint: Use === for comparison, not = assignment [OK]
Common Mistakes:
  • Confusing assignment and comparison operators
  • Forgetting to call next() in middleware
  • Using wrong HTTP status codes
5. You want to protect multiple routes so only users with roles 'admin' or 'manager' can access them. Which middleware implementation correctly allows this in Express?
hard
A. function checkRoles(req, res, next) { if(req.user.role === 'admin' && req.user.role === 'manager') next(); else res.status(403).send('Forbidden'); }
B. function checkRoles(req, res, next) { if(req.user.role === 'admin' || 'manager') next(); else res.status(403).send('Forbidden'); }
C. function checkRoles(req, res, next) { if(['admin', 'manager'].includes(req.user.role)) next(); else res.status(403).send('Forbidden'); }
D. function checkRoles(req, res, next) { if(req.user.role == 'admin' || req.user.role == 'manager') next(); else res.status(404).send('Forbidden'); }

Solution

  1. Step 1: Check role inclusion logic

    function checkRoles(req, res, next) { if(['admin', 'manager'].includes(req.user.role)) next(); else res.status(403).send('Forbidden'); } uses array includes() to check if role is 'admin' or 'manager', which is correct and clean.
  2. Step 2: Verify status code and logic correctness

    Using && requires role to be both 'admin' and 'manager' simultaneously (impossible); condition like if(role === 'admin' || 'manager') has wrong syntax and always passes since 'manager' is truthy; using 404 instead of 403 for forbidden access is incorrect.
  3. Final Answer:

    function checkRoles(req, res, next) { if(['admin', 'manager'].includes(req.user.role)) next(); else res.status(403).send('Forbidden'); } -> Option C
  4. Quick Check:

    Use includes() for multiple roles and 403 status = C [OK]
Hint: Use array includes() to check multiple roles cleanly [OK]
Common Mistakes:
  • Using incorrect logical operators or syntax
  • Checking role equality incorrectly
  • Sending wrong HTTP status code for forbidden
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard