Bird
Raised Fist0
Node.jsframework~20 mins

Middleware concept and execution flow in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Middleware Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Express middleware chain?
Consider this Express.js middleware setup. What will the server respond with when a GET request is made to '/'?
Node.js
const express = require('express');
const app = express();

app.use((req, res, next) => {
  req.message = 'Hello';
  next();
});

app.use((req, res, next) => {
  req.message += ' World';
  next();
});

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

app.listen(3000);
A"Hello World"
B"Hello"
C"World"
DError: req.message is undefined
Attempts:
2 left
💡 Hint
Think about how each middleware modifies the request object before the final handler.
❓ lifecycle
intermediate
2:00remaining
Which middleware runs first in this Express app?
Given this Express app, which middleware function executes first when a GET request to '/test' is received?
Node.js
const express = require('express');
const app = express();

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

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

app.get('/test', (req, res, next) => {
  console.log('Handler 1');
  next();
});

app.listen(3000);
AMiddleware 2
BHandler 1
CMiddleware 1
DNo middleware runs before handler
Attempts:
2 left
💡 Hint
Remember that app.use middlewares run before route handlers unless path or method restricts them.
📝 Syntax
advanced
2:00remaining
What error does this middleware code produce?
Examine this middleware function. What error will occur when a request is made?
Node.js
app.use((req, res, next) => {
  res.send('Hello');
  next();
});

app.use((req, res, next) => {
  res.send('World');
});
ANo error, works fine
BSyntaxError: Unexpected token
CTypeError: next is not a function
DError: Cannot set headers after they are sent to the client
Attempts:
2 left
💡 Hint
Think about what happens if you call next() after sending a response.
🔧 Debug
advanced
2:00remaining
Why does this middleware not modify the request as expected?
This middleware is supposed to add a user property to req, but it doesn't work. Why?
Node.js
app.use('/api', (req, res, next) => {
  req.user = { id: 1 };
  // missing next call
});

app.get('/api/data', (req, res) => {
  res.json(req.user);
});
ABecause req.user is overwritten later
BBecause next() is not called, the request hangs and never reaches the handler
CBecause the path '/api' does not match '/api/data'
DBecause res.json cannot send objects
Attempts:
2 left
💡 Hint
Middleware must call next() to continue the chain.
🧠 Conceptual
expert
3:00remaining
What is the correct order of middleware execution in Express?
Arrange these middleware and route handler steps in the order Express executes them for a matching request.
A2,3,1,4
B3,2,1,4
C2,1,3,4
D3,1,2,4
Attempts:
2 left
💡 Hint
Global middleware runs before route-specific middleware and handlers. Error middleware runs last if needed.

Practice

(1/5)
1. What is the main purpose of middleware in a Node.js Express app?
easy
A. To style the HTML pages
B. To directly send responses to the client without routes
C. To define database schemas
D. To run code on requests before they reach the route handlers

Solution

  1. Step 1: Understand middleware role and compare options

    Middleware functions run before route handlers to process requests. Only To run code on requests before they reach the route handlers describes middleware's role correctly; others describe unrelated tasks.
  2. Final Answer:

    To run code on requests before they reach the route handlers -> Option D
  3. Quick Check:

    Middleware = Pre-route code [OK]
Hint: Middleware runs before routes to handle requests [OK]
Common Mistakes:
  • Thinking middleware sends responses directly
  • Confusing middleware with database logic
  • Assuming middleware styles pages
2. Which of the following is the correct way to define a middleware function in Express?
easy
A. app.get((req, res) => { console.log('Middleware'); });
B. app.use((req, res, next) => { console.log('Middleware'); next(); });
C. app.middleware((req, res, next) => { next(); });
D. app.route('/').middleware((req, res) => { next(); });

Solution

  1. Step 1: Recall Express middleware syntax and check options

    Middleware uses app.use() with (req, res, next) parameters. Only app.use((req, res, next) => { console.log('Middleware'); next(); }); uses app.use() and calls next(), which is correct middleware syntax.
  2. Final Answer:

    app.use((req, res, next) => { console.log('Middleware'); next(); }); -> Option B
  3. Quick Check:

    Middleware = app.use + next() [OK]
Hint: Middleware uses app.use and calls next() [OK]
Common Mistakes:
  • Using app.get instead of app.use for middleware
  • Missing next() call inside middleware
  • Using non-existent app.middleware method
3. Consider this Express code:
app.use((req, res, next) => { console.log('First'); next(); });
app.use((req, res, next) => { console.log('Second'); next(); });
app.get('/', (req, res) => { res.send('Done'); });

What will be printed in the console when a GET request is made to '/'?
medium
A. First\nSecond
B. Second\nFirst
C. Done
D. No output

Solution

  1. Step 1: Understand middleware execution order and route handler

    Middleware runs in the order added: first prints 'First', then calls next(), second prints 'Second'. After middleware, route handler sends response but does not print to console.
  2. Final Answer:

    First\nSecond -> Option A
  3. Quick Check:

    Middleware order = console logs order [OK]
Hint: Middleware logs appear in order added before route runs [OK]
Common Mistakes:
  • Assuming route handler logs to console
  • Thinking middleware runs in reverse order
  • Missing next() causes no further logs
4. What is the problem with this middleware code?
app.use((req, res, next) => { console.log('Start'); });
app.get('/', (req, res) => { res.send('Hello'); });
medium
A. It calls next() twice, causing an error
B. It sends response twice, causing an error
C. It never calls next(), so the request hangs
D. It uses wrong parameters in middleware function

Solution

  1. Step 1: Check middleware function and request flow effect

    The middleware logs 'Start' but does not call next(), so it blocks further processing. Without next(), the route handler never runs, so the request hangs.
  2. Final Answer:

    It never calls next(), so the request hangs -> Option C
  3. Quick Check:

    Missing next() blocks request [OK]
Hint: Always call next() in middleware unless sending response [OK]
Common Mistakes:
  • Forgetting to call next() in middleware
  • Calling next() multiple times
  • Confusing middleware parameters
5. You want to add two middleware functions to log request time and check authentication before handling routes. Which code correctly ensures both run in order and the route handler executes after?
hard
A. app.use((req, res, next) => { console.log('Time:', Date.now()); next(); });\napp.use((req, res, next) => { if(req.user) next(); else res.status(401).send('Unauthorized'); });\napp.get('/', (req, res) => { res.send('Welcome'); });
B. app.use((req, res) => { console.log('Time:', Date.now()); });\napp.use((req, res, next) => { if(req.user) next(); else res.status(401).send('Unauthorized'); });\napp.get('/', (req, res) => { res.send('Welcome'); });
C. app.use((req, res, next) => { if(req.user) next(); else res.status(401).send('Unauthorized'); });\napp.use((req, res, next) => { console.log('Time:', Date.now()); next(); });\napp.get('/', (req, res) => { res.send('Welcome'); });
D. app.get('/', (req, res) => { console.log('Time:', Date.now()); });\napp.use((req, res, next) => { if(req.user) next(); else res.status(401).send('Unauthorized'); });

Solution

  1. Step 1: Check middleware order, next() calls, and route handler execution

    app.use((req, res, next) => { console.log('Time:', Date.now()); next(); });\napp.use((req, res, next) => { if(req.user) next(); else res.status(401).send('Unauthorized'); });\napp.get('/', (req, res) => { res.send('Welcome'); }); runs time logger first, calls next(), then auth check middleware, which calls next() or sends response. Only if both middleware call next(), the route handler runs and sends 'Welcome'.
  2. Final Answer:

    app.use((req, res, next) => { console.log('Time:', Date.now()); next(); });\napp.use((req, res, next) => { if(req.user) next(); else res.status(401).send('Unauthorized'); });\napp.get('/', (req, res) => { res.send('Welcome'); }); -> Option A
  3. Quick Check:

    Middleware order + next() = correct flow [OK]
Hint: Middleware must call next() to continue chain in correct order [OK]
Common Mistakes:
  • Missing next() in first middleware
  • Reversing middleware order
  • Using app.get instead of app.use for 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