Bird
Raised Fist0
Node.jsframework~20 mins

Middleware vs decorator pattern in Node.js - Practice Questions

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Middleware vs Decorator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Understanding Middleware Purpose
In Node.js web frameworks, what is the primary role of middleware functions?
ATo handle HTTP requests and responses in a sequence, allowing modification or termination of the request flow.
BTo manage database connections and queries automatically.
CTo compile JavaScript code into machine code for faster execution.
DTo decorate classes by adding new methods or properties at runtime.
Attempts:
2 left
💡 Hint
Think about how requests are processed step-by-step in a server.
❓ component_behavior
intermediate
2:00remaining
Decorator Pattern Behavior
What does a decorator function typically do in Node.js when applied to another function?
ADeletes the original function from memory to save space.
BAutomatically logs all errors thrown by the function without changing it.
CReplaces the original function with a completely unrelated function.
DWraps the original function to extend or modify its behavior without changing its code.
Attempts:
2 left
💡 Hint
Think about how you might add extra features to a function without rewriting it.
📝 Syntax
advanced
2:00remaining
Middleware Function Syntax
Which of the following is the correct syntax for a middleware function in Express.js?
Afunction(req, res, next) { console.log('Middleware'); next(); }
Bfunction(req, res) { console.log('Middleware'); next(); }
Cfunction(err, req, res, next) { console.log('Middleware'); next(); }
Dfunction(req, res, next) { console.log('Middleware'); }
Attempts:
2 left
💡 Hint
Middleware needs to call next() to continue the chain.
🔧 Debug
advanced
2:00remaining
Decorator Pattern Bug Identification
Given this decorator function, which option will cause a runtime error when used to decorate a function?
Node.js
function decorator(fn) {
  return function(...args) {
    console.log('Before');
    const result = fn(...args);
    console.log('After');
    return result;
  };
}
Aconst decorated = decorator(function() { return 42; }); decorated();
Bconst decorated = decorator(null); decorated();
Cconst decorated = decorator(() => 'ok'); decorated();
Dconst decorated = decorator(() => { throw new Error('Fail'); }); decorated();
Attempts:
2 left
💡 Hint
Consider what happens if fn is not a function.
❓ state_output
expert
3:00remaining
Middleware vs Decorator Output Difference
Consider this Express middleware and decorator usage. What will be logged when a request hits the server?
Node.js
const express = require('express');
const app = express();

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

function logDecorator(fn) {
  return function(req, res) {
    console.log('Decorator start');
    fn(req, res);
    console.log('Decorator end');
  };
}

app.use(logMiddleware);

app.get('/', logDecorator((req, res) => {
  console.log('Handler');
  res.send('Hello');
}));
A
Decorator start
Middleware start
Handler
Decorator end
Middleware end
B
Middleware start
Handler
Decorator start
Decorator end
Middleware end
C
Middleware start
Decorator start
Handler
Decorator end
Middleware end
D
Middleware start
Decorator start
Decorator end
Handler
Middleware end
Attempts:
2 left
💡 Hint
Think about the order middleware and route handlers run in Express.

Practice

(1/5)
1. What is the main difference between middleware and decorator patterns in Node.js?
easy
A. Middleware wraps functions; decorators process requests in a chain.
B. Middleware is only for error handling; decorators only for logging.
C. Middleware and decorators are the same and used interchangeably.
D. Middleware processes requests in a chain; decorators wrap functions to add behavior.

Solution

  1. Step 1: Understand middleware role

    Middleware functions run one after another to handle requests or responses in a chain.
  2. Step 2: Understand decorator role

    Decorators wrap a function to add or modify its behavior without changing the original function.
  3. Final Answer:

    Middleware processes requests in a chain; decorators wrap functions to add behavior. -> Option D
  4. Quick Check:

    Middleware = chain, Decorator = wrap [OK]
Hint: Middleware chains; decorators wrap functions [OK]
Common Mistakes:
  • Confusing middleware with decorators
  • Thinking middleware wraps functions
  • Assuming both are identical
2. Which of the following is the correct way to define a middleware function in Express.js?
easy
A. function middleware(req, res, next) { next(); }
B. function middleware(req, res) { return next(); }
C. function middleware(next, req, res) { next(); }
D. function middleware(res, req, next) { next(); }

Solution

  1. Step 1: Recall Express middleware signature

    Middleware functions take three parameters in order: request, response, and next function.
  2. Step 2: Check parameter order and usage

    function middleware(req, res, next) { next(); } correctly uses (req, res, next) and calls next() to pass control.
  3. Final Answer:

    function middleware(req, res, next) { next(); } -> Option A
  4. Quick Check:

    Middleware signature = (req, res, next) [OK]
Hint: Middleware params order: req, res, next [OK]
Common Mistakes:
  • Mixing parameter order
  • Forgetting to call next()
  • Returning next() instead of calling
3. Consider this decorator function in Node.js:
function logDecorator(fn) {
  return function(...args) {
    console.log('Calling function');
    return fn(...args);
  };
}

function greet(name) {
  return `Hello, ${name}!`;
}

const decoratedGreet = logDecorator(greet);
console.log(decoratedGreet('Alice'));

What will be printed to the console?
medium
A. Calling function\nHello, Alice!
B. Hello, Alice!\nCalling function
C. Calling function
D. Hello, Alice!

Solution

  1. Step 1: Understand decorator behavior

    The decorator wraps greet, logging 'Calling function' before calling greet.
  2. Step 2: Trace function calls and output

    Calling decoratedGreet('Alice') logs 'Calling function' then returns 'Hello, Alice!'. Both are printed by console.log.
  3. Final Answer:

    Calling function\nHello, Alice! -> Option A
  4. Quick Check:

    Decorator logs then calls function [OK]
Hint: Decorator logs before calling wrapped function [OK]
Common Mistakes:
  • Assuming only greeting prints
  • Confusing order of console logs
  • Missing decorator wrapping effect
4. This Express middleware is intended to log request URLs but has a bug:
function logger(req, res, next) {
  console.log('Request URL:', req.url);
  next;
}

What is the bug and how to fix it?
medium
A. Middleware must return a value; fix by adding return next()
B. req.url is undefined; fix by using req.path
C. next is not called as a function; fix by changing to next()
D. console.log syntax is wrong; fix by adding parentheses

Solution

  1. Step 1: Identify middleware flow control

    Middleware must call next() as a function to continue the chain.
  2. Step 2: Spot the bug in next usage

    Code uses next without parentheses, so next middleware is never called.
  3. Final Answer:

    next is not called as a function; fix by changing to next() -> Option C
  4. Quick Check:

    Call next() to continue middleware chain [OK]
Hint: Always call next() as a function in middleware [OK]
Common Mistakes:
  • Writing next instead of next()
  • Assuming req.url is invalid
  • Thinking middleware must return a value
5. You want to add authentication to an existing function without changing it. Which pattern fits best and why?
function fetchData(userId) {
  return `Data for user ${userId}`;
}
hard
A. Modify fetchData directly to add authentication logic inside.
B. Use a decorator to wrap fetchData and check authentication before calling it.
C. Use middleware to process fetchData since it handles requests in a chain.
D. Use middleware to wrap fetchData because middleware wraps functions.

Solution

  1. Step 1: Understand the goal

    You want to add authentication without changing fetchData itself.
  2. Step 2: Choose the right pattern

    Decorators wrap functions to add behavior like authentication without modifying original code.
  3. Final Answer:

    Use a decorator to wrap fetchData and check authentication before calling it. -> Option B
  4. Quick Check:

    Decorator = add behavior without changing function [OK]
Hint: Decorator wraps function to add features without changes [OK]
Common Mistakes:
  • Confusing middleware with decorators
  • Modifying original function directly
  • Thinking middleware wraps functions
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