Bird
Raised Fist0
Node.jsframework~20 mins

Building custom middleware 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
1:30remaining
What is the output of this custom middleware logging request method and URL?
Consider this Express.js middleware that logs the HTTP method and URL of incoming requests. What will be printed to the console when a GET request is made to '/home'?
Node.js
function logRequest(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next();
}

// Simulated request object
const req = { method: 'GET', url: '/home' };
const res = {};
logRequest(req, res, () => console.log('Next middleware called'));
A/home GET\nNext middleware called
BNext middleware called\nGET /home
CGET /home\nNext middleware called
DGET /home
Attempts:
2 left
💡 Hint
Look at the order of console.log statements and the use of next()
❓ state_output
intermediate
1:30remaining
What is the value of res.locals.user after this middleware runs?
Given this middleware that sets a user object on res.locals, what will be the value of res.locals.user after it executes?
Node.js
function setUser(req, res, next) {
  res.locals.user = { id: 42, name: 'Alice' };
  next();
}

const res = { locals: {} };
setUser({}, res, () => {});
console.log(res.locals.user);
A{}
B{ id: 42, name: 'Alice' }
Cundefined
Dnull
Attempts:
2 left
💡 Hint
res.locals is used to pass data between middleware and routes
📝 Syntax
advanced
2:00remaining
Which option correctly defines error-handling middleware in Express?
Express error-handling middleware must have a specific function signature. Which of these options correctly defines such middleware?
Afunction errorHandler(err, req, res, next) { res.status(500).send('Error'); }
Bfunction errorHandler(req, res, next) { res.status(500).send('Error'); }
Cfunction errorHandler(err, req, res) { res.status(500).send('Error'); }
Dfunction errorHandler(req, res) { res.status(500).send('Error'); }
Attempts:
2 left
💡 Hint
Error middleware must have four parameters: err, req, res, next
🔧 Debug
advanced
2:00remaining
Why does this custom middleware cause the server to hang?
This middleware logs the request but the server never responds or moves on. What is the cause?
Node.js
function logAndForget(req, res, next) {
  console.log('Request received');
  // missing next() call
}

// Usage in Express app
// app.use(logAndForget);
AMiddleware does not call next(), so request never proceeds
BMiddleware throws an error but does not handle it
CMiddleware calls next() twice causing a crash
DMiddleware modifies req object incorrectly
Attempts:
2 left
💡 Hint
Middleware must call next() or end the response
🧠 Conceptual
expert
2:30remaining
Which statement best describes the order of middleware execution in Express?
Given multiple middleware functions registered in an Express app, how does Express decide the order in which to run them?
AMiddleware runs only if the previous middleware sends a response
BMiddleware runs in reverse order of registration, always running all middleware regardless of next()
CMiddleware runs in parallel asynchronously, order does not matter
DMiddleware runs in the order they are added to the app, stopping if a middleware does not call next()
Attempts:
2 left
💡 Hint
Think about how Express processes middleware functions sequentially

Practice

(1/5)
1. What is the main purpose of custom middleware in a Node.js Express app?
easy
A. To directly send HTML pages to the client
B. To add extra processing steps between receiving a request and sending a response
C. To replace the Express router completely
D. To store data permanently in a database

Solution

  1. Step 1: Understand middleware role

    Middleware functions run between receiving a request and sending a response, allowing extra processing.
  2. Step 2: Identify correct purpose

    Custom middleware adds steps like logging, authentication, or modifying requests before response.
  3. Final Answer:

    To add extra processing steps between receiving a request and sending a response -> Option B
  4. Quick Check:

    Middleware = extra processing steps [OK]
Hint: Middleware adds steps between request and response [OK]
Common Mistakes:
  • Thinking middleware sends responses directly always
  • Confusing middleware with routing
  • Assuming middleware stores data permanently
2. Which of the following is the correct syntax to define a simple middleware function in Express?
easy
A. app.use = function(req, res, next) { console.log('Hi'); next(); }
B. app.middleware(req, res, next) { console.log('Hi'); next(); }
C. app.use(req, res, next) => { console.log('Hi'); next(); }
D. app.use((req, res, next) => { console.log('Hi'); next(); });

Solution

  1. Step 1: Recall Express middleware syntax

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

    app.use((req, res, next) => { console.log('Hi'); next(); }); correctly uses app.use with an arrow function and calls next(). Others have syntax errors.
  3. Final Answer:

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

    app.use + (req, res, next) function = correct [OK]
Hint: Middleware uses app.use with (req, res, next) function [OK]
Common Mistakes:
  • Missing parentheses around parameters
  • Assigning app.use instead of calling it
  • Using arrow function without parentheses for multiple params
3. Consider this middleware code snippet:
app.use((req, res, next) => {
  req.customValue = 42;
  next();
});
app.get('/', (req, res) => {
  res.send(`Value is ${req.customValue}`);
});

What will be the response when a client requests '/'?
medium
A. Value is 42
B. Value is undefined
C. Error: req.customValue is not defined
D. Empty response

Solution

  1. Step 1: Understand middleware effect on req object

    The middleware adds a property customValue with 42 to the req object and calls next() to continue.
  2. Step 2: Check route handler usage

    The route handler reads req.customValue and sends it in the response string.
  3. Final Answer:

    Value is 42 -> Option A
  4. Quick Check:

    Middleware sets req.customValue = 42 [OK]
Hint: Middleware can add properties to req used later [OK]
Common Mistakes:
  • Assuming req.customValue is lost after middleware
  • Thinking next() stops execution
  • Expecting error without setting property
4. Identify the error in this middleware code:
app.use((req, res, next) => {
  if (!req.headers['x-auth']) {
    res.status(401).send('Unauthorized');
  }
  next();
});
medium
A. Calling next() after sending a response causes error
B. Missing call to next() inside the if block
C. Headers should be accessed as req.header, not req.headers
D. Middleware must always send a response

Solution

  1. Step 1: Analyze middleware flow

    If 'x-auth' header is missing, response is sent with 401 status, ending the request.
  2. Step 2: Check next() call after response

    Calling next() after sending a response causes Express to continue processing, leading to errors.
  3. Final Answer:

    Calling next() after sending a response causes error -> Option A
  4. Quick Check:

    Do not call next() after res.send [OK]
Hint: Don't call next() after sending response [OK]
Common Mistakes:
  • Calling next() after res.send causing double response
  • Assuming headers property name is wrong
  • Thinking middleware must always send response
5. You want to create middleware that logs request method and URL only for POST requests. Which code correctly implements this?
hard
A. app.use((req, res, next) => { if (req.method = 'POST') console.log(req.method, req.url); next(); });
B. app.use((req, res, next) => { if (req.method === 'post') console.log(req.method, req.url); next(); });
C. app.use((req, res, next) => { if (req.method === 'POST') console.log(req.method, req.url); next(); });
D. app.use((req, res, next) => { if (req.method === POST) console.log(req.method, req.url); next(); });

Solution

  1. Step 1: Check condition for POST method

    Correct comparison uses '===' and string 'POST' in uppercase.
  2. Step 2: Verify logging and next call

    app.use((req, res, next) => { if (req.method === 'POST') console.log(req.method, req.url); next(); }); logs method and URL only if method is POST, then calls next() to continue.
  3. Final Answer:

    app.use((req, res, next) => { if (req.method === 'POST') console.log(req.method, req.url); next(); }); -> Option C
  4. Quick Check:

    Use strict equality and uppercase 'POST' [OK]
Hint: Use === 'POST' to check method string correctly [OK]
Common Mistakes:
  • Using single = instead of === for comparison
  • Using lowercase 'post' instead of uppercase
  • Using undefined POST variable without quotes
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