Bird
Raised Fist0
Expressframework~10 mins

Permission middleware in Express - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Permission middleware
Request received
Permission middleware runs
Check user permissions
Call next
Route handler
When a request comes in, the permission middleware checks if the user has rights. If yes, it passes control to the next handler; if no, it stops and sends a forbidden error.
Execution Sample
Express
function permissionMiddleware(req, res, next) {
  if (req.user?.role === 'admin') {
    next();
  } else {
    res.status(403).send('Forbidden');
  }
}
This middleware checks if the user role is 'admin'. If yes, it allows the request to continue; otherwise, it blocks with a 403 error.
Execution Table
StepActionCheckResultNext Step
1Middleware calledreq.user?.role === 'admin'trueCall next() to continue
2Route handler executesN/ARequest handledResponse sent
3Middleware calledreq.user?.role === 'admin'falseSend 403 Forbidden response
4Response endsN/ARequest blockedNo further handlers called
💡 Execution stops either by calling next() if permission granted or sending 403 if denied.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
req.user.roleundefined or 'admin' or other'admin''user''admin' or 'user'
next calledfalsetruefalsetrue or false
response status200 by default200403200 or 403
Key Moments - 2 Insights
Why does the middleware call next() only when the user role is 'admin'?
Because the middleware checks if req.user.role equals 'admin' (see execution_table step 1). If true, next() is called to continue processing; otherwise, it sends a 403 response and stops.
What happens if req.user is undefined?
The optional chaining (req.user?.role) safely returns undefined, so the condition fails and the middleware sends a 403 Forbidden response (see execution_table step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at step 3 when the user role is not 'admin'?
AThe middleware sends a 403 Forbidden response
BThe middleware calls next() to continue
CThe route handler executes normally
DThe request is redirected
💡 Hint
Check the 'Result' and 'Next Step' columns in execution_table row 3
According to variable_tracker, what is the value of 'next called' after step 1 if the user role is 'admin'?
Afalse
Bundefined
Ctrue
Dnull
💡 Hint
Look at 'next called' value after Step 1 in variable_tracker
If req.user is undefined, how does the middleware behave according to the execution flow?
ACalls next() and continues
BSends 403 Forbidden response
CThrows an error
DSkips middleware
💡 Hint
Refer to key_moments explanation about optional chaining and execution_table step 3
Concept Snapshot
Permission middleware in Express:
- Function checks user permissions from req.user
- If permission granted, call next() to continue
- If denied, send 403 Forbidden response
- Use optional chaining to avoid errors if user missing
- Stops request flow on denial, allowing secure routes
Full Transcript
Permission middleware in Express runs when a request arrives. It checks if the user has the right role, for example 'admin'. If yes, it calls next() to let the request continue to the route handler. If no, it sends a 403 Forbidden response and stops further processing. Optional chaining helps avoid errors if the user object is missing. This middleware protects routes by blocking unauthorized users.

Practice

(1/5)
1. What is the main purpose of permission middleware in an Express app?
easy
A. To check if a user has rights to access a route before running its handler
B. To format the response data before sending it to the client
C. To log every request made to the server
D. To handle errors thrown by route handlers

Solution

  1. Step 1: Understand middleware role

    Middleware runs before route handlers to control flow or check conditions.
  2. Step 2: Identify permission middleware function

    Permission middleware specifically checks user rights to allow or deny access.
  3. Final Answer:

    To check if a user has rights to access a route before running its handler -> Option A
  4. Quick Check:

    Permission middleware controls access = A [OK]
Hint: Permission middleware controls access before route runs [OK]
Common Mistakes:
  • Confusing permission middleware with logging middleware
  • Thinking it formats response data
  • Assuming it handles errors
2. Which of the following is the correct way to define a permission middleware function in Express?
easy
A. function checkPermission(req, res, next) { if (!req.user) next('No user'); else next(); }
B. function checkPermission(req, res) { if (!req.user) res.send('No user'); else next(); }
C. function checkPermission(req, res, next) { if (!req.user) res.send('No user'); else next(); }
D. function checkPermission(req, res, next) { if (!req.user) return; else next(); }

Solution

  1. Step 1: Check middleware signature

    Express middleware must have three parameters: req, res, next.
  2. Step 2: Verify correct usage of next()

    If permission fails, respond or send error; else call next() to continue.
  3. Final Answer:

    function checkPermission(req, res, next) { if (!req.user) res.send('No user'); else next(); } -> Option C
  4. Quick Check:

    Middleware needs (req, res, next) and calls next() [OK]
Hint: Middleware needs three params: req, res, next [OK]
Common Mistakes:
  • Missing next parameter
  • Calling next() without parentheses
  • Not sending response or calling next() properly
3. Given this middleware and route, what will be the response if req.user.role is 'guest'?
function permitAdmin(req, res, next) {
  if (req.user?.role !== 'admin') {
    return res.status(403).send('Forbidden');
  }
  next();
}

app.get('/admin', permitAdmin, (req, res) => {
  res.send('Welcome Admin');
});
medium
A. Forbidden
B. Welcome Admin
C. Internal Server Error
D. No response (timeout)

Solution

  1. Step 1: Check user role in middleware

    The middleware checks if req.user.role is not 'admin'. Here it is 'guest', so condition is true.
  2. Step 2: Middleware response on failed permission

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

    Forbidden -> Option A
  4. Quick Check:

    Role not admin = 403 Forbidden [OK]
Hint: If role not admin, middleware sends 403 and stops [OK]
Common Mistakes:
  • Assuming route handler runs anyway
  • Confusing status codes
  • Missing optional chaining on req.user
4. Identify the error in this permission middleware code:
function checkPermission(req, res, next) {
  if (!req.user.permissions.includes('edit')) {
    res.status(401).send('Unauthorized');
  }
  next();
}
medium
A. Middleware should not call next() at all
B. Wrong status code for unauthorized access
C. Incorrect property name 'permissions' on req.user
D. Missing return after sending response, so next() runs anyway

Solution

  1. Step 1: Analyze flow after sending response

    After res.status(401).send(), the code continues and calls next(), allowing next middleware or route to run.
  2. Step 2: Fix by adding return to stop execution

    Adding 'return' before res.status(401).send() prevents next() from running when unauthorized.
  3. Final Answer:

    Missing return after sending response, so next() runs anyway -> Option D
  4. Quick Check:

    Send response must return to stop next() [OK]
Hint: Return after res.send() to prevent next() running [OK]
Common Mistakes:
  • Not returning after sending response
  • Using wrong HTTP status code
  • Assuming next() should never be called
5. You want to create a permission middleware that allows access only if the user has at least one role from an array of allowed roles. Which code correctly implements this?
hard
A. function permitRoles(allowedRoles) { return (req, res, next) => { if (!allowedRoles.includes(req.user.role)) { res.status(403).send('Forbidden'); } next(); }; }
B. function permitRoles(allowedRoles) { return (req, res, next) => { if (allowedRoles.some(role => role === req.user.role)) { next(); } else { res.status(403).send('Forbidden'); } }; }
C. function permitRoles(allowedRoles) { return (req, res, next) => { if (allowedRoles.indexOf(req.user.role) === -1) { res.status(403).send('Forbidden'); } next(); }; }
D. function permitRoles(allowedRoles) { return (req, res, next) => { if (allowedRoles.every(role => role !== req.user.role)) { next(); } else { res.status(403).send('Forbidden'); } }; }

Solution

  1. Step 1: Understand the requirement

    Access allowed if user role matches any role in allowedRoles array.
  2. Step 2: Check each option logic

    function permitRoles(allowedRoles) { return (req, res, next) => { if (!allowedRoles.includes(req.user.role)) { res.status(403).send('Forbidden'); } next(); }; } uses includes but misses return before res.send(), so next() runs anyway. function permitRoles(allowedRoles) { return (req, res, next) => { if (allowedRoles.indexOf(req.user.role) === -1) { res.status(403).send('Forbidden'); } next(); }; } misses return before res.send(), so next() runs anyway. function permitRoles(allowedRoles) { return (req, res, next) => { if (allowedRoles.some(role => role === req.user.role)) { next(); } else { res.status(403).send('Forbidden'); } }; } uses some() to check if any role matches, then calls next() or sends 403 correctly. function permitRoles(allowedRoles) { return (req, res, next) => { if (allowedRoles.every(role => role !== req.user.role)) { next(); } else { res.status(403).send('Forbidden'); } }; } reverses logic, allowing access if no match, which is wrong.
  3. Step 3: Choose best correct code

    function permitRoles(allowedRoles) { return (req, res, next) => { if (allowedRoles.some(role => role === req.user.role)) { next(); } else { res.status(403).send('Forbidden'); } }; } correctly implements the logic with proper flow control.
  4. Final Answer:

    Uses some() to allow access if any role matches, else sends 403 -> Option B
  5. Quick Check:

    Use some() to check roles and control flow correctly [OK]
Hint: Use some() to check if user role is in allowed roles [OK]
Common Mistakes:
  • Not returning after sending response
  • Using every() incorrectly
  • Calling next() even after forbidden response