Bird
Raised Fist0
Expressframework~20 mins

Conditional middleware execution in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Express Middleware Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
Middleware execution based on request path
Consider this Express middleware setup. What will be the output when a GET request is made to /api/data?
Express
const express = require('express');
const app = express();

function logMiddleware(req, res, next) {
  console.log('Middleware triggered');
  next();
}

app.use((req, res, next) => {
  if (req.path.startsWith('/api')) {
    logMiddleware(req, res, next);
  } else {
    next();
  }
});

app.get('/api/data', (req, res) => {
  res.send('Data response');
});

app.listen(3000);
AConsole logs nothing and client receives 404 Not Found.
BConsole logs nothing and client receives 'Data response'.
CConsole logs 'Middleware triggered' but client hangs without response.
DConsole logs 'Middleware triggered' and client receives 'Data response'.
Attempts:
2 left
💡 Hint
Think about when the middleware function is called based on the request path.
📝 Syntax
intermediate
2:00remaining
Correct conditional middleware syntax
Which option correctly applies middleware only for POST requests to '/submit' in Express?
Aapp.post('/submit', (req, res, next) => { next(); });
Bapp.use((req, res, next) => { if (req.path === '/submit' && req.method === 'POST') next(); else next(); });
Capp.use('/submit', (req, res, next) => { if (req.method === 'POST') next(); else res.sendStatus(405); });
D;)} ;)504(sutatSdnes.ser esle ;)(txen )'TSOP' === dohtem.qer( fi { >= )txen ,ser ,qer( ,'timbus/'(esu.ppa
Attempts:
2 left
💡 Hint
Remember the difference between app.use and app.post for method-specific middleware.
🔧 Debug
advanced
2:00remaining
Middleware not executing as expected
Given this code, why does the middleware never log 'Middleware active' when accessing '/dashboard'?
Express
const express = require('express');
const app = express();

app.use('/dashboard', (req, res, next) => {
  console.log('Middleware active');
  next();
});

app.get('/dashboard', (req, res) => {
  res.send('Dashboard page');
});

app.listen(3000);
ABecause the middleware is applied after the route handler, so it never runs.
BBecause app.use with a path only matches requests starting with that path, so it should work and the problem is elsewhere.
CBecause the middleware is applied to '/dashboard' but the request path includes a trailing slash '/dashboard/', so it doesn't match.
DBecause the middleware is synchronous and blocks the route handler.
Attempts:
2 left
💡 Hint
Check how Express matches paths with and without trailing slashes.
❓ state_output
advanced
2:00remaining
Middleware modifying request state conditionally
What will be the value of req.user in the route handler after this middleware runs for a request to '/profile' with header Authorization: Bearer token123?
Express
const express = require('express');
const app = express();

app.use((req, res, next) => {
  if (req.headers.authorization?.startsWith('Bearer ')) {
    req.user = { id: 1, name: 'Alice' };
  }
  next();
});

app.get('/profile', (req, res) => {
  res.json(req.user || null);
});

app.listen(3000);
A{"id":1,"name":"Alice"}
Bnull
Cundefined
DThrows a TypeError
Attempts:
2 left
💡 Hint
Look at how the middleware sets req.user based on the Authorization header.
🧠 Conceptual
expert
3:00remaining
Understanding conditional middleware order and effect
In Express, if you want to run a logging middleware only for routes starting with '/admin' and ensure it runs before any route handler, which setup is correct?
APlace <code>app.use(loggerMiddleware)</code> after all '/admin' routes are defined and check path inside middleware.
BDefine <code>app.get('/admin/*', loggerMiddleware, handler)</code> for each route individually.
CPlace <code>app.use('/admin', loggerMiddleware)</code> before defining any '/admin' routes.
DUse <code>app.use((req, res, next) => { if (req.path.startsWith('/admin')) loggerMiddleware(req, res, next); else next(); })</code> after routes.
Attempts:
2 left
💡 Hint
Middleware order matters in Express; earlier middleware runs before later routes.

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