Bird
Raised Fist0
Expressframework~5 mins

Middleware factory pattern in Express - Cheat Sheet & Quick Revision

Choose your learning style10 modes available
Recall & Review
beginner
What is a middleware factory in Express?
A middleware factory is a function that returns a middleware function. It allows you to create middleware with custom settings or parameters.
Click to reveal answer
beginner
Why use a middleware factory instead of a simple middleware function?
Middleware factories let you customize behavior by passing arguments when creating the middleware, making your code reusable and flexible.
Click to reveal answer
intermediate
Example: What does this middleware factory do?
<pre>function logger(level) {
  return function(req, res, next) {
    console.log(`[${level}] ${req.method} ${req.url}`);
    next();
  };
}</pre>
This factory creates a logger middleware that logs the HTTP method and URL with a custom log level like 'INFO' or 'DEBUG'.
Click to reveal answer
beginner
How do you apply a middleware created by a factory in Express?
Call the factory with parameters to get the middleware, then use it with app.use or route handlers, e.g., app.use(logger('INFO')).
Click to reveal answer
intermediate
What is the benefit of middleware factories for code maintenance?
They keep code DRY (Don't Repeat Yourself) by letting you write one factory and create many customized middleware instances from it.
Click to reveal answer
What does a middleware factory return in Express?
AA database connection
BA route handler
CAn Express app instance
DA middleware function
Why might you pass parameters to a middleware factory?
ATo customize middleware behavior
BTo start the server
CTo define routes
DTo connect to a database
How do you use a middleware factory in an Express app?
AUse the factory as a database model
BCall the factory and pass the result to app.use()
CImport the factory as a route
DCall app.listen() with the factory
Which of these is NOT a benefit of middleware factories?
AAutomatic database queries
BCode reuse
CCustomizable middleware
DCleaner code
What is the main difference between a middleware factory and a regular middleware?
AFactory connects to database; regular middleware logs requests
BFactory runs the server; regular middleware handles requests
CFactory returns middleware; regular middleware is the middleware itself
DFactory is a route; regular middleware is a template
Explain how a middleware factory works in Express and why it is useful.
Think about how you can create middleware that changes behavior based on input.
You got /4 concepts.
    Describe a simple example of a middleware factory and how you would use it in an Express app.
    Imagine you want to log requests with different levels.
    You got /4 concepts.

      Practice

      (1/5)
      1. What is the main purpose of the middleware factory pattern in Express?
      easy
      A. To automatically handle errors in middleware
      B. To create middleware functions that can be customized with different settings
      C. To replace the need for routing in Express
      D. To speed up server response time by caching

      Solution

      1. Step 1: Understand middleware factory pattern concept

        The middleware factory pattern is used to create middleware functions that accept parameters to customize their behavior.
      2. Step 2: Compare options with the concept

        Only To create middleware functions that can be customized with different settings correctly describes creating customizable middleware functions. Other options describe unrelated features.
      3. Final Answer:

        To create middleware functions that can be customized with different settings -> Option B
      4. Quick Check:

        Middleware factory pattern = customizable middleware [OK]
      Hint: Middleware factory = function returning middleware with parameters [OK]
      Common Mistakes:
      • Thinking it automatically handles errors
      • Confusing with routing or caching
      • Believing it speeds response time directly
      2. Which of the following is the correct syntax for a middleware factory function in Express?
      easy
      A. function logger() { /* middleware code */ }
      B. function logger(req, res, next) { return function(level) { /* middleware code */ } }
      C. function logger(level) { return function(req, res, next) { /* middleware code */ } }
      D. function logger(level, req, res, next) { /* middleware code */ }

      Solution

      1. Step 1: Identify middleware factory structure

        A middleware factory is a function that takes parameters and returns a middleware function with signature (req, res, next).
      2. Step 2: Match syntax to this pattern

        function logger(level) { return function(req, res, next) { /* middleware code */ } } matches this: it takes 'level' and returns a function with (req, res, next). Others do not follow this pattern.
      3. Final Answer:

        function logger(level) { return function(req, res, next) { /* middleware code */ } } -> Option C
      4. Quick Check:

        Factory returns middleware function = function logger(level) { return function(req, res, next) { /* middleware code */ } } [OK]
      Hint: Factory takes params, returns (req, res, next) function [OK]
      Common Mistakes:
      • Placing req, res, next in factory parameters
      • Not returning a middleware function
      • Confusing middleware and factory signatures
      3. Given the middleware factory below, what will be logged when a request is made?
      function greet(name) {
        return function(req, res, next) {
          console.log(`Hello, ${name}!`);
          next();
        };
      }
      
      app.use(greet('Alice'));
      medium
      A. Hello, Alice!
      B. Hello, undefined!
      C. Hello, name!
      D. No output, middleware does not log

      Solution

      1. Step 1: Understand middleware factory usage

        The factory greet('Alice') returns a middleware that logs 'Hello, Alice!'.
      2. Step 2: Predict middleware behavior on request

        When a request comes, the middleware logs the greeting with the name 'Alice'.
      3. Final Answer:

        Hello, Alice! -> Option A
      4. Quick Check:

        Factory param used in log = Hello, Alice! [OK]
      Hint: Factory param appears in log output [OK]
      Common Mistakes:
      • Expecting 'undefined' if factory param missing
      • Thinking middleware does not log
      • Confusing variable name with string literal
      4. Identify the error in this middleware factory code:
      function checkRole(role) {
        return function(req, res, next) {
          if(req.user.role === role) {
            next;
          } else {
            res.status(403).send('Forbidden');
          }
        };
      }
      medium
      A. res.status should be res.send
      B. Incorrect comparison operator in if statement
      C. Middleware factory should not return a function
      D. Missing parentheses when calling next()

      Solution

      1. Step 1: Review middleware function call

        Inside middleware, next must be called as a function: next().
      2. Step 2: Identify the error

        The code uses 'next;' instead of 'next();', so middleware will not proceed correctly.
      3. Final Answer:

        Missing parentheses when calling next() -> Option D
      4. Quick Check:

        Call next() with parentheses [OK]
      Hint: Always call next() as a function, not just next [OK]
      Common Mistakes:
      • Writing next without parentheses
      • Confusing status and send methods
      • Thinking factory should not return a function
      5. You want to create a middleware factory that limits requests based on a max count per user. Which approach correctly applies the middleware factory pattern to achieve this?
      hard
      A. function rateLimiter(maxRequests) { const counts = new Map(); return function(req, res, next) { const user = req.user.id; counts.set(user, (counts.get(user) || 0) + 1); if(counts.get(user) > maxRequests) { res.status(429).send('Too many requests'); } else { next(); } }; }
      B. function rateLimiter(req, res, next, maxRequests) { // logic here }
      C. function rateLimiter(maxRequests) { return function(req, res) { // missing next call }; }
      D. function rateLimiter() { // no parameters, fixed limit }

      Solution

      1. Step 1: Understand the requirement for customizable limit

        The middleware must accept maxRequests as a parameter to customize the limit.
      2. Step 2: Check which option correctly returns middleware with (req, res, next) and uses maxRequests

        function rateLimiter(maxRequests) { const counts = new Map(); return function(req, res, next) { const user = req.user.id; counts.set(user, (counts.get(user) || 0) + 1); if(counts.get(user) > maxRequests) { res.status(429).send('Too many requests'); } else { next(); } }; } correctly implements a factory that returns middleware tracking counts and enforcing maxRequests, calling next() properly.
      3. Final Answer:

        function rateLimiter(maxRequests) { const counts = new Map(); return function(req, res, next) { const user = req.user.id; counts.set(user, (counts.get(user) || 0) + 1); if(counts.get(user) > maxRequests) { res.status(429).send('Too many requests'); } else { next(); } }; } -> Option A
      4. Quick Check:

        Factory with param returns middleware calling next() = function rateLimiter(maxRequests) { const counts = new Map(); return function(req, res, next) { const user = req.user.id; counts.set(user, (counts.get(user) || 0) + 1); if(counts.get(user) > maxRequests) { res.status(429).send('Too many requests'); } else { next(); } }; } [OK]
      Hint: Factory takes limit param, returns middleware calling next() [OK]
      Common Mistakes:
      • Putting next as a factory parameter
      • Not calling next() in middleware
      • Not using maxRequests parameter
      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