Bird
Raised Fist0
Node.jsframework~20 mins

Why middleware is fundamental in Node.js - Challenge Your Understanding

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!
🧠 Conceptual
intermediate
2:00remaining
What is the primary role of middleware in Node.js web frameworks?

Middleware functions are used in Node.js web frameworks like Express. What is their main purpose?

ATo compile JavaScript code into machine code for faster execution
BTo directly send HTML pages to the client without any processing
CTo handle requests and responses by processing data before reaching the final route handler
DTo replace the need for a database in the application
Attempts:
2 left
💡 Hint

Think about how middleware acts between the client request and the final response.

❓ component_behavior
intermediate
2:00remaining
How does middleware affect the flow of request handling?

Consider this Express middleware chain:

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 '/'?

ASecond\nFirst
BFirst\nSecond
CDone
DNo output because next() is missing
Attempts:
2 left
💡 Hint

Middleware functions run in the order they are added and call next() to continue.

📝 Syntax
advanced
2:00remaining
Identify the error in this middleware function

Look at this middleware code snippet:

app.use((req, res, next) => {
  if (!req.user) {
    res.status(401).send('Unauthorized');
  }
  next();
});

What problem will this cause when a request has no user?

AIt will send 'Unauthorized' but then call next(), causing headers to be sent twice error
BIt will throw a syntax error because next() is missing parentheses
CIt will not send any response and hang forever
DIt will correctly block unauthorized requests without errors
Attempts:
2 left
💡 Hint

Think about what happens after sending a response in middleware.

❓ state_output
advanced
2:00remaining
What is the final response body after this middleware chain?

Given this Express setup:

app.use((req, res, next) => {
  req.customData = 'Hello';
  next();
});
app.use((req, res, next) => {
  req.customData += ' World';
  next();
});
app.get('/', (req, res) => {
  res.send(req.customData);
});

What will the client receive when requesting '/'?

AAn error because req.customData is undefined
B"Hello"
C"World"
D"Hello World"
Attempts:
2 left
💡 Hint

Middleware can add or change properties on the request object.

🔧 Debug
expert
2:00remaining
Why does this middleware never end the request?

Examine this middleware:

app.use((req, res, next) => {
  if (req.path === '/stop') {
    return res.send('Stopped');
  } else {
    next();
  }
});

Requests to '/stop' hang and never complete. Why?

ABecause the middleware is missing a return statement after res.send() to stop execution
BBecause the middleware does not call next() for '/stop' paths, so Express waits forever
CBecause res.send() is asynchronous and needs await keyword
DBecause res.send() is called but next() is not stopped, causing the request to hang
Attempts:
2 left
💡 Hint

Think about what happens after res.send() inside an if block.

Practice

(1/5)
1. What is the main role of middleware in a Node.js application?
easy
A. To run code between receiving a request and sending a response
B. To directly send HTML pages to the client
C. To store data permanently in a database
D. To compile JavaScript code into machine code

Solution

  1. Step 1: Understand middleware position in request flow

    Middleware functions run after a request is received but before the response is sent back.
  2. Step 2: Identify middleware purpose

    Middleware is used to process or modify requests and responses, like logging or authentication, not to send pages or store data directly.
  3. Final Answer:

    To run code between receiving a request and sending a response -> Option A
  4. Quick Check:

    Middleware = code between request and response [OK]
Hint: Middleware runs between request and response [OK]
Common Mistakes:
  • Thinking middleware sends the final response directly
  • Confusing middleware with database operations
  • Assuming middleware compiles code
2. Which of the following is the correct way to define a middleware function in Express.js?
easy
A. app.use((req, res, next) => { console.log('Middleware'); next(); });
B. app.get((req, res) => { console.log('Middleware'); });
C. app.listen((req, res, next) => { next(); });
D. app.middleware((req, res, next) => { next(); });

Solution

  1. Step 1: Recall Express middleware syntax

    Middleware is added using app.use() with a function that takes req, res, and next parameters.
  2. Step 2: Check each option

    app.use((req, res, next) => { console.log('Middleware'); next(); }); uses app.use() correctly and calls next() to pass control. Others use wrong methods or miss next().
  3. Final Answer:

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

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

What will be printed in the console when a request is made?
medium
A. First\nSecond\nThird
B. First\nSecond
C. Second\nThird
D. First only

Solution

  1. Step 1: Trace middleware execution order

    Middleware runs in order. First logs 'First' and calls next(), so second runs next.
  2. Step 2: Check response behavior in second middleware

    Second logs 'Second' and sends response with res.send('Done'), ending the request cycle. Third middleware is not called.
  3. Final Answer:

    First\nSecond -> Option B
  4. Quick Check:

    Middleware stops after res.send() [OK]
Hint: Middleware stops after res.send() without next() [OK]
Common Mistakes:
  • Assuming all middleware always run
  • Ignoring that res.send() ends response
  • Thinking next() is called automatically after res.send()
4. You wrote this middleware but your app crashes with an error:
app.use((req, res) => { console.log('Logging request'); });

What is the problem?
medium
A. Middleware must send a response directly
B. Middleware cannot use console.log
C. Middleware must have three parameters: req, res, and next
D. Middleware should be defined after app.listen()

Solution

  1. Step 1: Check middleware function parameters

    Express middleware needs three parameters: req, res, and next to pass control to next middleware.
  2. Step 2: Identify missing next parameter

    The given middleware only has req and res, so it cannot call next(), causing the app to hang or crash.
  3. Final Answer:

    Middleware must have three parameters: req, res, and next -> Option C
  4. Quick Check:

    Middleware needs next parameter [OK]
Hint: Middleware needs (req, res, next) parameters [OK]
Common Mistakes:
  • Omitting the next parameter
  • Thinking console.log causes errors
  • Believing middleware must always send response
5. You want to add middleware that logs request method and URL, then checks if user is authenticated before continuing. Which code correctly combines these tasks?
hard
A. app.use((req, res, next) => { console.log(req.method, req.url); next(); res.send('Unauthorized'); });
B. app.use((req, res) => { console.log(req.method, req.url); next(); if (!req.user) res.send('Unauthorized'); });
C. app.use((req, res, next) => { if (!req.user) next(); console.log(req.method, req.url); next(); });
D. app.use((req, res, next) => { console.log(req.method, req.url); if (!req.user) return res.status(401).send('Unauthorized'); next(); });

Solution

  1. Step 1: Log request method and URL first

    app.use((req, res, next) => { console.log(req.method, req.url); if (!req.user) return res.status(401).send('Unauthorized'); next(); }); logs method and URL immediately, which is correct for logging middleware.
  2. Step 2: Check authentication before calling next()

    app.use((req, res, next) => { console.log(req.method, req.url); if (!req.user) return res.status(401).send('Unauthorized'); next(); }); checks if req.user exists; if not, it sends 401 response and stops. Otherwise, it calls next() to continue.
  3. Step 3: Verify other options

    The other options misuse next() or res.send(), causing incorrect flow or multiple calls.
  4. Final Answer:

    app.use((req, res, next) => { console.log(req.method, req.url); if (!req.user) return res.status(401).send('Unauthorized'); next(); }); -> Option D
  5. Quick Check:

    Log then check auth, call next() only if authorized [OK]
Hint: Log first, then check auth, call next() only if authorized [OK]
Common Mistakes:
  • Calling next() after sending response
  • Not stopping middleware on unauthorized access
  • Logging after next() causing missed logs
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