Bird
Raised Fist0
Expressframework~10 mins

Middleware composition for auth layers 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 - Middleware composition for auth layers
Request Received
Middleware 1: Check Token
Middleware 2: Check Role
Next Middleware or Route Handler
The request passes through each middleware in order. Each middleware checks a condition (token, role). If a check fails, it sends an error response and stops. If all pass, the request proceeds.
Execution Sample
Express
app.use(checkToken);
app.use(checkRole);
app.get('/data', (req, res) => {
  res.send('Secret Data');
});
This code runs two middleware functions in order before the route handler. Each middleware checks authorization and either passes control or sends an error.
Execution Table
StepMiddlewareCheckCondition ResultActionResponse Sent
1checkTokenIs token valid?YesCall next()No
2checkRoleIs role allowed?YesCall next()No
3Route HandlerN/AN/ASend 'Secret Data'Yes
4EndN/AN/ARequest completedNo
💡 Request completes successfully after passing all middleware checks and reaching route handler.
Variable Tracker
VariableStartAfter checkTokenAfter checkRoleFinal
req.userundefined{id:1, role:'admin'}{id:1, role:'admin'}{id:1, role:'admin'}
res.statusCode200200200200
responseSentfalsefalsefalsetrue
Key Moments - 3 Insights
Why does the request stop if the token is invalid?
Because in the execution_table row 1, if the token check fails, the middleware sends a 401 response and does not call next(), stopping further middleware.
What happens if the role check fails?
As shown in execution_table row 2, if the role is not allowed, the middleware sends a 403 response and does not call next(), so the route handler is not reached.
Why is the route handler only called after all middleware pass?
Because each middleware calls next() only if its check passes, allowing the request to continue to the next middleware or route handler, as seen in rows 1 and 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the responseSent value after checkRole middleware if the role is allowed?
Atrue
Bundefined
Cfalse
Dnull
💡 Hint
Check the 'responseSent' variable in variable_tracker after 'After checkRole' column.
At which step does the request send the 'Secret Data' response?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at execution_table row where 'Route Handler' sends the response.
If the token is invalid, what action does the middleware take?
ASends 401 Unauthorized and stops
BCalls next() to continue
CSends 403 Forbidden and stops
DIgnores and continues
💡 Hint
Refer to execution_table step 1 where token validity is checked.
Concept Snapshot
Middleware composition in Express:
- Middleware run in order on each request
- Each middleware checks auth (token, role)
- If check fails, send error response and stop
- If passes, call next() to continue
- Route handler runs after all middleware pass
Full Transcript
Middleware composition for auth layers in Express means running multiple middleware functions one after another. Each middleware checks something about the request, like if the token is valid or if the user role is allowed. If a check fails, the middleware sends an error response and stops the request from going further. If the check passes, it calls next() to let the request continue to the next middleware or the final route handler. This way, the request only reaches the route handler if all auth checks pass.

Practice

(1/5)
1. What is the main purpose of composing multiple middleware functions for authentication in Express?
easy
A. To run several small auth checks in order before allowing access
B. To combine all auth logic into one big function
C. To skip authentication for faster response
D. To handle database queries inside middleware

Solution

  1. Step 1: Understand middleware composition

    Middleware composition means running multiple middleware functions one after another.
  2. Step 2: Purpose in auth layers

    Using multiple small auth checks in order helps keep code clean and checks each condition separately.
  3. Final Answer:

    To run several small auth checks in order before allowing access -> Option A
  4. Quick Check:

    Middleware composition = multiple small auth checks [OK]
Hint: Think of middleware as a chain of small checks [OK]
Common Mistakes:
  • Thinking all auth logic must be in one function
  • Believing middleware skips auth
  • Confusing middleware with database queries
2. Which of the following is the correct way to apply two middleware functions checkToken and checkRole to an Express route using an array?
easy
A. app.get('/admin', checkToken, checkRole, (req, res) => res.send('OK'))
B. app.get('/admin', checkToken && checkRole, (req, res) => res.send('OK'))
C. app.get('/admin', [checkToken, checkRole], (req, res) => res.send('OK'))
D. app.get('/admin', checkToken || checkRole, (req, res) => res.send('OK'))

Solution

  1. Step 1: Understand Express middleware syntax

    Express accepts multiple middleware as an array or separate arguments before the handler. This question specifies using an array.
  2. Step 2: Check each option

    A uses separate arguments. B and D use logical operators which are invalid here. C correctly uses an array.
  3. Final Answer:

    app.get('/admin', [checkToken, checkRole], (req, res) => res.send('OK')) -> Option C
  4. Quick Check:

    Middleware array syntax = app.get('/admin', [checkToken, checkRole], (req, res) => res.send('OK')) [OK]
Hint: Use arrays to group middleware in routes [OK]
Common Mistakes:
  • Using logical operators instead of arrays
  • Passing middleware as a single combined expression
  • Forgetting to include middleware before handler
3. Given the middleware functions below, what will be the response when a request with req.user = { role: 'user' } hits the route?
function checkToken(req, res, next) {
  if (!req.user) return res.status(401).send('No token');
  next();
}

function checkAdmin(req, res, next) {
  if (req.user.role !== 'admin') return res.status(403).send('Forbidden');
  next();
}

app.get('/secure', [checkToken, checkAdmin], (req, res) => res.send('Welcome admin'));
medium
A. Welcome admin
B. Forbidden
C. No token
D. Internal Server Error

Solution

  1. Step 1: Analyze checkToken middleware

    It checks if req.user exists. Here req.user is { role: 'user' }, so it passes and calls next().
  2. Step 2: Analyze checkAdmin middleware

    It checks if req.user.role is 'admin'. Here it is 'user', so it returns 403 Forbidden response.
  3. Final Answer:

    Forbidden -> Option B
  4. Quick Check:

    Role check fails = Forbidden [OK]
Hint: Check middleware order and conditions carefully [OK]
Common Mistakes:
  • Assuming role 'user' passes admin check
  • Ignoring middleware that sends response early
  • Confusing status codes
4. Identify the error in this middleware composition code:
function auth(req, res, next) {
  if (!req.headers.authorization) {
    res.status(401).send('Unauthorized');
  }
  next();
}

app.get('/data', auth, (req, res) => res.send('Data'));
medium
A. Missing return after sending 401 response, so next() runs anyway
B. Middleware should be async function
C. Route handler missing res.end() call
D. Authorization header check should be in route handler

Solution

  1. Step 1: Check middleware flow

    If authorization header is missing, it sends 401 but does not stop execution.
  2. Step 2: Identify missing return

    Without return after res.status(401).send(), next() is called anyway, causing route handler to run incorrectly.
  3. Final Answer:

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

    Send response must stop middleware with return [OK]
Hint: Always return after sending response in middleware [OK]
Common Mistakes:
  • Calling next() after sending response
  • Thinking async needed for simple middleware
  • Putting auth logic in route handler
5. You want to create a reusable middleware group for routes that require both token validation and admin role check. Which is the best way to compose and apply these middlewares in Express?
hard
A. Use a global app.use() for all routes regardless of auth needs
B. Create a single middleware combining both checks and use it in routes
C. Call each middleware manually inside the route handler function
D. Use an array of separate middlewares and apply the array to routes

Solution

  1. Step 1: Understand middleware grouping

    Grouping middlewares as an array keeps each check separate and reusable.
  2. Step 2: Compare options

    Use an array of separate middlewares and apply the array to routes uses an array of middlewares applied to routes, which is clean and composable. Create a single middleware combining both checks and use it in routes merges checks into one, losing modularity. Call each middleware manually inside the route handler function is manual and error-prone. Use a global app.use() for all routes regardless of auth needs applies auth globally, which is not selective.
  3. Final Answer:

    Use an array of separate middlewares and apply the array to routes -> Option D
  4. Quick Check:

    Middleware arrays = reusable and clean [OK]
Hint: Group middlewares in arrays for reuse [OK]
Common Mistakes:
  • Combining all logic into one middleware
  • Calling middleware inside handlers manually
  • Applying auth globally without route control