Bird
Raised Fist0
Expressframework~20 mins

Router level middleware in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Router Middleware Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does router-level middleware affect request handling?
Consider an Express app with a router that has middleware attached. What happens when a request matches a route inside that router?
Express
const express = require('express');
const app = express();
const router = express.Router();

router.use((req, res, next) => {
  req.customValue = 'hello';
  next();
});

router.get('/test', (req, res) => {
  res.send(req.customValue);
});

app.use('/api', router);

// What will be the response when a client requests GET /api/test ?
AThe response will be empty because the middleware does not call next().
BThe response will be undefined because router middleware does not modify req object.
CThe response will be an error because middleware cannot set properties on req.
DThe response will be 'hello' because the router middleware sets req.customValue before the route handler.
Attempts:
2 left
💡 Hint
Router middleware runs before route handlers inside that router and can modify req and res objects.
📝 Syntax
intermediate
2:00remaining
Identify the correct syntax to apply router-level middleware
Which option correctly applies middleware only to routes inside a router in Express?
Express
const express = require('express');
const router = express.Router();

// Middleware to log request method
function logMethod(req, res, next) {
  console.log(req.method);
  next();
}

// Apply middleware here

router.get('/hello', (req, res) => {
  res.send('Hi');
});
Arouter.use(logMethod);
Bapp.use('/router', logMethod);
Crouter.get(logMethod);
Dapp.use(logMethod);
Attempts:
2 left
💡 Hint
Router-level middleware is applied with router.use() before defining routes.
🔧 Debug
advanced
2:00remaining
Why does this router-level middleware not run?
Given this code, why does the middleware not log anything when requesting /api/data? const express = require('express'); const app = express(); const router = express.Router(); router.get('/data', (req, res) => { res.send('Data'); }); router.use((req, res, next) => { console.log('Middleware ran'); next(); }); app.use('/api', router);
AMiddleware is missing the next parameter.
BMiddleware must call res.send() to run.
CMiddleware is defined after the route, so it never runs for matched routes.
DMiddleware must be defined on app, not router.
Attempts:
2 left
💡 Hint
Order of middleware and routes matters in Express.
❓ state_output
advanced
2:00remaining
What is the value of req.processed after these middlewares?
Analyze the following router-level middleware sequence: const express = require('express'); const router = express.Router(); router.use((req, res, next) => { req.processed = 1; next(); }); router.use((req, res, next) => { req.processed += 2; next(); }); router.get('/check', (req, res) => { res.send(String(req.processed)); });
A'3'
B'1'
C'2'
Dundefined
Attempts:
2 left
💡 Hint
Middleware runs in order and can modify req object cumulatively.
🧠 Conceptual
expert
2:00remaining
Which statement about router-level middleware is true?
Select the correct statement about router-level middleware in Express.
ARouter-level middleware runs for every request to the app regardless of the path.
BRouter-level middleware runs only if the request path matches the router's mount path and the middleware is defined before the route handlers.
CRouter-level middleware cannot modify the request or response objects.
DRouter-level middleware must always end the response and cannot call next().
Attempts:
2 left
💡 Hint
Think about when router middleware runs and how it interacts with routes.

Practice

(1/5)
1. What is the main purpose of router-level middleware in Express?
easy
A. To replace the main app middleware completely
B. To run middleware only for routes defined in a specific router
C. To handle errors globally across all routers
D. To serve static files from a directory

Solution

  1. Step 1: Understand router-level middleware scope

    Router-level middleware runs only for routes defined in that router, not the entire app.
  2. Step 2: Compare with other middleware types

    Main app middleware runs for all routes, error middleware handles errors, static middleware serves files. Router middleware is specific to router routes.
  3. Final Answer:

    To run middleware only for routes defined in a specific router -> Option B
  4. Quick Check:

    Router middleware scope = specific router routes [OK]
Hint: Router middleware affects only its router's routes [OK]
Common Mistakes:
  • Confusing router middleware with app-level middleware
  • Thinking router middleware handles errors globally
  • Assuming router middleware serves static files
2. Which of the following is the correct way to add middleware to an Express router?
easy
A. router.middleware(function(req, res, next) { next(); });
B. router.add(function(req, res, next) { next(); });
C. app.useRouter(function(req, res, next) { next(); });
D. router.use(function(req, res, next) { next(); });

Solution

  1. Step 1: Recall Express router middleware syntax

    The correct method to add middleware to a router is router.use().
  2. Step 2: Check other options for validity

    router.middleware, app.useRouter, and router.add are not valid Express methods.
  3. Final Answer:

    router.use(function(req, res, next) { next(); }); -> Option D
  4. Quick Check:

    Use router.use() to add middleware [OK]
Hint: Use router.use() to add middleware to routers [OK]
Common Mistakes:
  • Using non-existent methods like router.middleware or router.add
  • Confusing app.useRouter with router.use
  • Forgetting to call next() inside middleware
3. Consider this Express router code:
const express = require('express');
const router = express.Router();

router.use((req, res, next) => {
  console.log('Middleware A');
  next();
});

router.get('/test', (req, res) => {
  res.send('Hello from test');
});

module.exports = router;

What will be printed in the console when a client requests /test on this router?
medium
A. Middleware A
B. Hello from test
C. Middleware A and then Hello from test
D. Nothing will be printed

Solution

  1. Step 1: Identify middleware behavior on route request

    The router middleware logs 'Middleware A' and calls next(), so it runs before the route handler.
  2. Step 2: Understand console output vs response

    The console.log prints 'Middleware A' to the server console. The response sends 'Hello from test' to the client but does not print to console.
  3. Final Answer:

    Middleware A -> Option A
  4. Quick Check:

    Middleware console.log prints 'Middleware A' [OK]
Hint: Middleware logs to console, route sends response [OK]
Common Mistakes:
  • Confusing console output with response content
  • Expecting both console and response text in console
  • Ignoring the next() call in middleware
4. Given this router code:
const router = require('express').Router();

router.use((req, res, next) => {
  console.log('First middleware');
  next();
});

router.get('/hello', (req, res) => {
  res.send('Hello World');
});

router.use((req, res) => {
});

What is the problem with this code?
medium
A. The last middleware does not call next(), causing requests to hang
B. The last middleware is missing next() and will cause 404 for all routes
C. The last middleware will never run because it is after a route handler
D. The last middleware should have 4 parameters to handle errors

Solution

  1. Step 1: Analyze middleware execution order

    Middleware and routes execute in the order defined. First middleware runs for all requests and calls next().
  2. Step 2: Trace unmatched route behavior

    For unmatched routes like /foo: first middleware calls next(), /hello route doesn't match so next(), last middleware runs but does nothing--no response and no next() call.
  3. Step 3: Identify the consequence

    The request pipeline stops without a response, causing the client request to hang indefinitely.
  4. Final Answer:

    The last middleware does not call next(), causing requests to hang -> Option A
  5. Quick Check:

    No response + no next() = request hangs [OK]
Hint: Every middleware must either respond or call next() [OK]
Common Mistakes:
  • Thinking empty catch-all middleware is harmless
  • Forgetting unmatched routes reach the last middleware
  • Assuming the router automatically handles 404s
5. You want to apply a logging middleware only to routes under /api in your Express app. You create a router and add middleware like this:
const express = require('express');
const app = express();
const apiRouter = express.Router();

apiRouter.use((req, res, next) => {
  console.log('API request:', req.method, req.url);
  next();
});

apiRouter.get('/users', (req, res) => {
  res.send('User list');
});

app.use('/api', apiRouter);

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

What will happen when a client requests /api/users and /?
hard
A. Logging middleware does not run for any route
B. Logging middleware runs for both /api/users and /
C. Logging middleware runs only for /api/users, not for /
D. Logging middleware runs only for / route

Solution

  1. Step 1: Understand router mounting path

    The router is mounted at '/api', so its middleware runs only for routes starting with '/api'.
  2. Step 2: Analyze requests

    Request to '/api/users' triggers the router middleware and route handler. Request to '/' goes directly to app.get('/') and skips router middleware.
  3. Final Answer:

    Logging middleware runs only for /api/users, not for / -> Option C
  4. Quick Check:

    Router middleware runs only on mounted path routes [OK]
Hint: Router middleware runs only on its mounted path routes [OK]
Common Mistakes:
  • Assuming router middleware runs for all app routes
  • Confusing app-level and router-level middleware scopes
  • Expecting middleware to run for '/' when mounted on '/api'
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