📖 Scenario: You are building a simple Express server that fetches user data. To speed up responses, you want to add a cache middleware that stores user data temporarily.
🎯 Goal: Create an Express middleware called cacheMiddleware that stores user data in a cache object. When a request comes in, the middleware should check if the user data is in the cache and return it immediately if found. Otherwise, it should let the request continue to fetch fresh data.
📋 What You'll Learn
Create a cache object to store user data keyed by user ID
Create a middleware function called cacheMiddleware
In the middleware, check if the requested user ID is in the cache
If cached data exists, send it as JSON response and do not call next()
If no cached data, call next() to continue to the route handler
In the route handler, fetch user data and store it in the cache
Send the user data as JSON response
💡 Why This Matters
🌍 Real World
Caching is used in web servers to speed up responses by storing frequently requested data temporarily.
💼 Career
Understanding middleware and caching is important for backend developers to build efficient and scalable web applications.
Progress0 / 4 steps
1
Create the cache object
Create an empty object called cache to store cached user data.
Express
Hint
Think of cache as a simple box where you keep user data for quick access.
2
Create the cache middleware
Create a middleware function called cacheMiddleware that takes req, res, and next as parameters.
Express
Hint
This function will check if data is in the cache before the route handler runs.
3
Add cache check logic in middleware
Inside cacheMiddleware, get userId from req.params. If cache[userId] exists, send it as JSON response and do not call next(). Otherwise, call next().
Express
Hint
Use req.params.userId to find the user ID from the URL.
4
Use middleware and cache data in route
Add a GET route at /user/:userId that uses cacheMiddleware. In the route handler, create a userData object with id and name. Store userData in cache[userId] and send it as JSON response.
Express
Hint
This route uses the middleware to check cache before creating new user data.
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
Step 1: Understand cache middleware role
Cache middleware stores responses temporarily to avoid repeating expensive operations.
Step 2: Compare with other middleware roles
Authentication, parsing, and logging serve different purposes unrelated to caching.
Final Answer:
To store responses and speed up repeated requests -> Option B
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
Step 1: Check middleware signature
Express middleware functions take (req, res, next) in that order.
Step 2: Verify control flow
If cached data exists, send it; otherwise, call next() to continue processing.
Final Answer:
function cache(req, res, next) { if (cacheData) res.send(cacheData); else next(); } -> Option C
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' }?
cacheData is defined as { message: 'Hello' }, so the if condition is true.
Step 2: Determine middleware behavior
Since cacheData exists, middleware sends JSON response and does not call next().
Final Answer:
{"message":"Hello"} -> Option A
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
Step 1: Analyze control flow
If cacheData exists, res.send(cacheData) sends a response, but next() is still called afterward.
Step 2: Understand Express behavior
Calling next() after sending a response can cause errors or duplicate responses.
Final Answer:
next() is called even after sending a response -> Option D
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
Step 1: Understand cache expiration logic
Cache should store data with a timestamp and check age before sending cached response.
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.
Final Answer:
Store response in cacheData with a timestamp; clear cacheData if older than 10 seconds before sending -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.