Bird
Raised Fist0
Expressframework~10 mins

Conditional middleware execution in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Conditional middleware execution
Request Received
↓
Check Condition in Middleware
↓
Run Middleware
↓
Next Middleware or Route Handler
↓
Send Response
The request comes in, middleware checks a condition. If true, middleware runs; if false, it skips to next handler.
Execution Sample
Express
app.use((req, res, next) => {
  if (req.path === '/special') {
    console.log('Special middleware runs');
    next();
  } else {
    next();
  }
});
Middleware runs only when the request path is '/special', otherwise it skips.
Execution Table
StepRequest PathCondition (req.path === '/special')ActionOutput/Next
1/homeFalseSkip middlewareCall next()
2/specialTrueRun middlewareLog 'Special middleware runs'
3/aboutFalseSkip middlewareCall next()
4/specialTrueRun middlewareLog 'Special middleware runs'
5/contactFalseSkip middlewareCall next()
💡 Middleware runs only when condition is true; otherwise, it calls next() to continue.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5
req.path/home/special/about/special/contact—
ConditionFalseTrueFalseTrueFalse—
Middleware RunsNoYesNoYesNo—
Key Moments - 2 Insights
Why does the middleware sometimes skip running?
Because the condition req.path === '/special' is false for those requests, so the middleware calls next() to skip itself (see execution_table rows 1, 3, 5).
What happens if next() is not called when skipping?
The request would hang because Express waits for next() to continue. Skipping middleware must call next() to pass control (see execution_table rows with 'Skip middleware').
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the middleware action at step 2?
ASkip middleware and call next()
BRun middleware and log message
CThrow an error
DSend response immediately
💡 Hint
Check the 'Action' column at step 2 in the execution_table.
At which step does the condition become false for the first time?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Condition' column in variable_tracker for the first false value.
If the condition was changed to req.path.startsWith('/special'), how would the middleware behave at step 3?
AIt would run middleware
BIt would throw an error
CIt would skip middleware
DIt would send response immediately
💡 Hint
Step 3 path is '/about', which does not start with '/special'. See condition logic.
Concept Snapshot
Conditional middleware runs only when a condition is true.
Use if statements inside middleware to check request properties.
Call next() to skip middleware and continue.
Helps run middleware only for specific routes or cases.
Always call next() unless sending response.
Full Transcript
In Express, middleware can run conditionally by checking request details like path. When a request comes in, middleware checks if the condition is true. If yes, it runs its code; if no, it calls next() to skip itself and let other middleware or route handlers run. This lets you run middleware only for certain routes or situations. For example, middleware can check if req.path equals '/special' and run only then. If the condition is false, it calls next() to continue. This prevents blocking the request. Always remember to call next() when skipping middleware, or the request will hang. This trace shows requests with different paths and how middleware runs or skips based on the condition.

Practice

(1/5)
1. What is the main purpose of conditional middleware in Express?
easy
A. To run middleware only when certain conditions are met
B. To run all middleware for every request without exception
C. To replace route handlers completely
D. To stop the server from accepting requests

Solution

  1. Step 1: Understand middleware role

    Middleware functions process requests and can modify them or respond.
  2. Step 2: Identify conditional middleware purpose

    Conditional middleware runs only when a specific condition is true, saving resources and controlling flow.
  3. Final Answer:

    To run middleware only when certain conditions are met -> Option A
  4. Quick Check:

    Conditional middleware = run only if condition true [OK]
Hint: Think: middleware runs only if condition matches [OK]
Common Mistakes:
  • Assuming middleware always runs for every request
  • Confusing middleware with route handlers
  • Thinking middleware stops server requests
2. Which of the following is the correct way to conditionally execute middleware based on the request path?
easy
A. app.use((req, res, next) => { if (req.path === '/admin') res.send('OK'); });
B. app.use((req, res, next) => { if (req.method === 'POST') res.send('Allowed'); else next(); });
C. app.use((req, res, next) => { if (req.path = '/admin') next(); else next(); });
D. app.use((req, res, next) => { if (req.path === '/admin') next(); else res.send('No access'); });

Solution

  1. Step 1: Check condition syntax

    app.use((req, res, next) => { if (req.path === '/admin') next(); else res.send('No access'); }); correctly uses '===' to compare req.path to '/admin'.
  2. Step 2: Verify middleware flow

    app.use((req, res, next) => { if (req.path === '/admin') next(); else res.send('No access'); }); calls next() only if path matches; otherwise, it sends a response, stopping further middleware.
  3. Final Answer:

    app.use((req, res, next) => { if (req.path === '/admin') next(); else res.send('No access'); }); -> Option D
  4. Quick Check:

    Correct condition and flow = app.use((req, res, next) => { if (req.path === '/admin') next(); else res.send('No access'); }); [OK]
Hint: Use '===' for comparison and call next() properly [OK]
Common Mistakes:
  • Using single '=' instead of '===' for comparison
  • Not calling next() to continue middleware chain
  • Sending response without ending middleware properly
3. Consider this middleware code snippet:
app.use((req, res, next) => {
  if (req.query.token === '123') {
    console.log('Token valid');
    next();
  } else {
    res.status(401).send('Unauthorized');
  }
});
app.get('/', (req, res) => res.send('Welcome!'));

What will be the output when a GET request is made to '/' with query ?token=123?
medium
A. Console logs 'Token valid' but response is 'Unauthorized'
B. Console logs 'Token valid' and response is 'Welcome!'
C. No response, request hangs
D. Response is 'Unauthorized' with status 401

Solution

  1. Step 1: Check token condition

    Request query token is '123', so condition is true and 'Token valid' logs.
  2. Step 2: Middleware calls next()

    Calling next() passes control to next handler, which sends 'Welcome!'.
  3. Final Answer:

    Console logs 'Token valid' and response is 'Welcome!' -> Option B
  4. Quick Check:

    Valid token triggers next() and welcome message [OK]
Hint: If condition true, next() runs next handler [OK]
Common Mistakes:
  • Assuming response is 'Unauthorized' despite valid token
  • Thinking middleware always sends response
  • Missing that next() continues to route handler
4. Identify the error in this conditional middleware:
app.use((req, res, next) => {
  if (req.headers['x-auth']) {
    next();
  }
  res.status(403).send('Forbidden');
});
medium
A. Middleware does not check request method
B. next() is called without arguments
C. Missing else block causes response sent twice
D. Headers property is misspelled

Solution

  1. Step 1: Analyze middleware flow

    If header exists, next() is called but code continues to send 403 response anyway.
  2. Step 2: Identify missing else

    Without else, response is sent after next(), causing errors or double responses.
  3. Final Answer:

    Missing else block causes response sent twice -> Option C
  4. Quick Check:

    Always use else or return after next() [OK]
Hint: Use else or return after next() to avoid double response [OK]
Common Mistakes:
  • Not using else or return after next()
  • Assuming next() stops code execution
  • Ignoring middleware flow after next()
5. You want to create middleware that only runs for POST requests to '/submit' and logs 'Processing submission'. Which code correctly implements this conditional middleware?
hard
A. app.use((req, res, next) => { if (req.path === '/submit' && req.method === 'POST') { console.log('Processing submission'); } next(); });
B. app.use('/submit', (req, res, next) => { if (req.method === 'POST') { console.log('Processing submission'); } next(); });
C. app.post('/submit', (req, res, next) => { console.log('Processing submission'); next(); });
D. app.use('/submit', (req, res, next) => { if (req.method = 'POST') { console.log('Processing submission'); next(); } });

Solution

  1. Step 1: Check condition for path and method

    app.use((req, res, next) => { if (req.path === '/submit' && req.method === 'POST') { console.log('Processing submission'); } next(); }); correctly checks both req.path and req.method inside middleware.
  2. Step 2: Confirm middleware calls next()

    app.use((req, res, next) => { if (req.path === '/submit' && req.method === 'POST') { console.log('Processing submission'); } next(); }); calls next() after logging, ensuring request continues.
  3. Step 3: Evaluate other options

    app.use('/submit', (req, res, next) => { if (req.method === 'POST') { console.log('Processing submission'); } next(); }); runs on all methods for '/submit', app.post('/submit', (req, res, next) => { console.log('Processing submission'); next(); }); is a route handler, app.use('/submit', (req, res, next) => { if (req.method = 'POST') { console.log('Processing submission'); next(); } }); uses '=' instead of '===' causing assignment error.
  4. Final Answer:

    app.use((req, res, next) => { if (req.path === '/submit' && req.method === 'POST') { console.log('Processing submission'); } next(); }); -> Option A
  5. Quick Check:

    Check both path and method, call next() [OK]
Hint: Check both path and method inside middleware, then call next() [OK]
Common Mistakes:
  • Using assignment '=' instead of comparison '==='
  • Not calling next() after middleware logic
  • Confusing route handlers with middleware
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