Bird
Raised Fist0
Expressframework~20 mins

Cache middleware pattern in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Cache Middleware Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does this cache middleware do when a cached response exists?

Consider this Express cache middleware snippet. What happens when a cached response is found?

Express
const cache = {};

function cacheMiddleware(req, res, next) {
  const key = req.originalUrl;
  if (cache[key]) {
    res.send(cache[key]);
  } else {
    res.sendResponse = res.send;
    res.send = (body) => {
      cache[key] = body;
      res.sendResponse(body);
    };
    next();
  }
}
AIt throws an error because res.send is overwritten incorrectly.
BIt sends the cached response immediately without calling next().
CIt clears the cache and then calls next().
DIt calls next() and then sends the cached response.
Attempts:
2 left
💡 Hint

Think about what happens when cache[key] exists and how res.send is used.

📝 Syntax
intermediate
2:00remaining
Which option correctly caches the response body in Express middleware?

Choose the correct way to cache the response body inside Express middleware.

Express
const cache = {};

function cacheMiddleware(req, res, next) {
  const key = req.originalUrl;
  if (cache[key]) {
    res.send(cache[key]);
  } else {
    res.sendResponse = res.send;
    res.send = (body) => {
      // Cache the body here
      res.sendResponse(body);
    };
    next();
  }
}
Acache[key] = body;
Bcache[key] == body;
Ccache[key] === body;
Dcache.key = body;
Attempts:
2 left
💡 Hint

Remember how to assign a value to an object property using a variable key.

🔧 Debug
advanced
2:00remaining
Why does this cache middleware cause the response to never send?

Identify the bug in this cache middleware that causes the client to hang without receiving a response.

Express
const cache = {};

function cacheMiddleware(req, res, next) {
  const key = req.originalUrl;
  if (cache[key]) {
    res.send(cache[key]);
  } else {
    res.send = (body) => {
      cache[key] = body;
      res.send(body);
    };
    next();
  }
}
Ares.send is overwritten and calls itself recursively causing a stack overflow.
Bcache[key] is never assigned so cache is always empty.
Cnext() is not called so the request hangs.
Dres.sendResponse is missing causing a syntax error.
Attempts:
2 left
💡 Hint

Look at how res.send is redefined and what happens when it calls res.send inside itself.

❓ state_output
advanced
2:00remaining
What is the cache content after these requests?

Given this cache middleware and two requests to '/data', what is the cache content after both requests?

Express
const cache = {};

function cacheMiddleware(req, res, next) {
  const key = req.originalUrl;
  if (cache[key]) {
    res.send(cache[key]);
  } else {
    res.sendResponse = res.send;
    res.send = (body) => {
      cache[key] = body;
      res.sendResponse(body);
    };
    next();
  }
}

// Simulated requests:
// 1st request to '/data' sends 'First response'
// 2nd request to '/data' sends 'Second response'

// Assume middleware is used correctly and responses are sent accordingly.
A{}
B{"/data": "Second response"}
C{"/data": "First response"}
D{"/data": null}
Attempts:
2 left
💡 Hint

Think about when the cache is updated and when the cached response is sent.

🧠 Conceptual
expert
3:00remaining
What is a key limitation of this simple cache middleware pattern?

Consider this cache middleware pattern that stores responses in memory keyed by URL. What is a key limitation of this approach in a real-world Express app?

Express
const cache = {};

function cacheMiddleware(req, res, next) {
  const key = req.originalUrl;
  if (cache[key]) {
    res.send(cache[key]);
  } else {
    res.sendResponse = res.send;
    res.send = (body) => {
      cache[key] = body;
      res.sendResponse(body);
    };
    next();
  }
}
AIt encrypts cached data to protect user privacy.
BIt automatically scales across multiple server instances without extra configuration.
CIt supports caching POST requests with different bodies automatically.
DIt does not handle cache invalidation or expiration, so stale data may be served indefinitely.
Attempts:
2 left
💡 Hint

Think about what happens if the data changes but the cache never updates or clears.

Practice

(1/5)
1. What is the main purpose of cache middleware in an Express app?
easy
A. To handle user authentication
B. To store responses and speed up repeated requests
C. To parse incoming JSON data
D. To log all incoming requests

Solution

  1. Step 1: Understand cache middleware role

    Cache middleware stores responses temporarily to avoid repeating expensive operations.
  2. Step 2: Compare with other middleware roles

    Authentication, parsing, and logging serve different purposes unrelated to caching.
  3. Final Answer:

    To store responses and speed up repeated requests -> Option B
  4. Quick Check:

    Cache middleware = store responses [OK]
Hint: Cache middleware speeds up repeated requests by storing responses [OK]
Common Mistakes:
  • Confusing cache with authentication middleware
  • Thinking cache parses request bodies
  • Assuming cache logs requests
2. Which of the following is the correct way to define a simple cache middleware function in Express?
easy
A. function cache(req, res, next) { next(); res.send(cacheData); }
B. function cache(req, res) { res.send(cacheData); next(); }
C. function cache(req, res, next) { if (cacheData) res.send(cacheData); else next(); }
D. function cache(req, next, res) { if (cacheData) res.send(cacheData); else next(); }

Solution

  1. Step 1: Check middleware signature

    Express middleware functions take (req, res, next) in that order.
  2. Step 2: Verify control flow

    If cached data exists, send it; otherwise, call next() to continue processing.
  3. Final Answer:

    function cache(req, res, next) { if (cacheData) res.send(cacheData); else next(); } -> Option C
  4. Quick Check:

    Middleware signature and flow = function cache(req, res, next) { if (cacheData) res.send(cacheData); else next(); } [OK]
Hint: Middleware must have (req, res, next) and call next() if no cache [OK]
Common Mistakes:
  • Wrong parameter order in middleware function
  • Calling next() after sending response
  • Not calling next() when cache miss
3. Given this cache middleware snippet, what will be the output if cacheData is { message: 'Hello' }?
function cache(req, res, next) {
  if (cacheData) {
    res.json(cacheData);
  } else {
    next();
  }
}

app.get('/greet', cache, (req, res) => {
  res.json({ message: 'Hi there!' });
});
medium
A. {"message":"Hello"}
B. {"message":"Hi there!"}
C. Error: cacheData is undefined
D. No response sent

Solution

  1. Step 1: Check cacheData value

    cacheData is defined as { message: 'Hello' }, so the if condition is true.
  2. Step 2: Determine middleware behavior

    Since cacheData exists, middleware sends JSON response and does not call next().
  3. Final Answer:

    {"message":"Hello"} -> Option A
  4. Quick Check:

    cacheData present sends cached response [OK]
Hint: If cacheData exists, middleware sends it and skips next() [OK]
Common Mistakes:
  • Assuming next() runs even if cacheData exists
  • Confusing JSON string with object
  • Expecting original handler response
4. Identify the bug in this cache middleware code:
let cacheData;

function cache(req, res, next) {
  if (cacheData) {
    res.send(cacheData);
  }
  next();
}
medium
A. Middleware function missing req parameter
B. cacheData is not initialized
C. res.send should be res.json
D. next() is called even after sending a response

Solution

  1. Step 1: Analyze control flow

    If cacheData exists, res.send(cacheData) sends a response, but next() is still called afterward.
  2. Step 2: Understand Express behavior

    Calling next() after sending a response can cause errors or duplicate responses.
  3. Final Answer:

    next() is called even after sending a response -> Option D
  4. Quick Check:

    Calling next() after res.send causes errors [OK]
Hint: Do not call next() after sending a response [OK]
Common Mistakes:
  • Calling next() unconditionally after res.send
  • Ignoring middleware flow control
  • Assuming res.send and next() can run together
5. You want to implement cache middleware that stores responses for 10 seconds and then expires. Which approach correctly achieves this in Express?
hard
A. Store response in cacheData with a timestamp; clear cacheData if older than 10 seconds before sending
B. Use setTimeout to clear cacheData every 10 seconds regardless of requests
C. Send cached response only if cacheData exists, without checking time
D. Clear cacheData manually by restarting the server every 10 seconds

Solution

  1. Step 1: Understand cache expiration logic

    Cache should store data with a timestamp and check age before sending cached response.
  2. Step 2: Evaluate options

    Store response in cacheData with a timestamp; clear cacheData if older than 10 seconds before sending checks timestamp and clears stale cache before responding, ensuring fresh data.
  3. Final Answer:

    Store response in cacheData with a timestamp; clear cacheData if older than 10 seconds before sending -> Option A
  4. Quick Check:

    Cache expiration needs timestamp check [OK]
Hint: Use timestamps to expire cache, not just timers or manual clears [OK]
Common Mistakes:
  • Ignoring cache expiration timing
  • Clearing cache blindly without request context
  • Relying on server restart to clear cache
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