Bird
Raised Fist0
Node.jsframework~30 mins

Middleware vs decorator pattern in Node.js - Hands-On Comparison

Choose your learning style10 modes available
Understanding Middleware vs Decorator Pattern in Node.js
📖 Scenario: You are building a simple Node.js server that processes requests. You want to understand how middleware and decorator patterns can help add features like logging and timing without changing the main logic.
🎯 Goal: Build a small Node.js example showing how to use middleware functions and a decorator function to add logging and timing features to a simple request handler.
📋 What You'll Learn
Create a basic request handler function named handleRequest that returns a string.
Create a middleware function named loggerMiddleware that logs the request info.
Create a middleware function named timerMiddleware that measures execution time.
Create a decorator function named decorateHandler that wraps handleRequest to add logging and timing.
Show how to apply middleware functions in sequence.
Show how to apply the decorator function to the handler.
💡 Why This Matters
🌍 Real World
Middleware and decorator patterns are common in Node.js servers to add features like logging, authentication, and timing without changing core logic.
💼 Career
Understanding these patterns helps developers write clean, modular, and maintainable server code, a key skill for backend development roles.
Progress0 / 4 steps
1
Create the basic request handler function
Create a function called handleRequest that takes no arguments and returns the string 'Request handled'.
Node.js
Hint

Define a simple function that returns a fixed string.

2
Create middleware functions for logging and timing
Create two middleware functions: loggerMiddleware and timerMiddleware. Each takes a next function as argument and returns a new function. loggerMiddleware should log 'Logging request' before calling next(). timerMiddleware should record start time, call next(), then log the elapsed time in milliseconds with console.log.
Node.js
Hint

Each middleware returns a function that calls next() with added behavior before or after.

3
Apply middleware functions in sequence to the handler
Create a variable called composedHandler that applies loggerMiddleware and timerMiddleware to handleRequest in this order: first loggerMiddleware, then timerMiddleware. Use function calls to wrap handleRequest accordingly.
Node.js
Hint

Wrap handleRequest first with loggerMiddleware, then wrap that result with timerMiddleware.

4
Create a decorator function to add logging and timing
Create a function called decorateHandler that takes a function fn as argument and returns a new function. The returned function should log 'Decorator logging', record start time, call fn(), then log the elapsed time with console.log. Then create a variable decoratedHandler by calling decorateHandler with handleRequest.
Node.js
Hint

The decorator returns a new function that adds logging and timing around the original function call.

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