What if your server could remember answers and save time without extra code everywhere?
Why Cache middleware pattern in Express? - Purpose & Use Cases
Imagine your web server fetching the same data from a slow database every time a user requests a page.
Each request waits, making users impatient and servers overloaded.
Manually checking and storing data for every request is messy and repetitive.
It clutters your code and slows down response times, causing frustrated users.
The cache middleware pattern stores data temporarily so repeated requests get instant answers.
This keeps your code clean and speeds up responses without extra work in each route.
app.get('/data', (req, res) => { database.query('SELECT * FROM table', (err, result) => { res.send(result); }); });
const cacheMiddleware = (req, res, next) => {
if (cache.has('data')) {
return res.send(cache.get('data'));
}
next();
};
app.get('/data', cacheMiddleware, (req, res) => {
database.query('SELECT * FROM table', (err, result) => {
cache.set('data', result);
res.send(result);
});
});It enables your server to respond faster and handle more users smoothly by reusing data smartly.
Think of a news website showing the same headlines to many visitors; caching avoids fetching headlines from the database every time.
Manual data fetching slows down your server and clutters code.
Cache middleware stores and reuses data automatically.
This pattern improves speed and keeps code clean and simple.
Practice
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 BQuick Check:
Cache middleware = store responses [OK]
- Confusing cache with authentication middleware
- Thinking cache parses request bodies
- Assuming cache logs requests
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 CQuick Check:
Middleware signature and flow = function cache(req, res, next) { if (cacheData) res.send(cacheData); else next(); } [OK]
- Wrong parameter order in middleware function
- Calling next() after sending response
- Not calling next() when cache miss
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!' });
});Solution
Step 1: Check cacheData value
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 AQuick Check:
cacheData present sends cached response [OK]
- Assuming next() runs even if cacheData exists
- Confusing JSON string with object
- Expecting original handler response
let cacheData;
function cache(req, res, next) {
if (cacheData) {
res.send(cacheData);
}
next();
}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 DQuick Check:
Calling next() after res.send causes errors [OK]
- Calling next() unconditionally after res.send
- Ignoring middleware flow control
- Assuming res.send and next() can run together
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 AQuick Check:
Cache expiration needs timestamp check [OK]
- Ignoring cache expiration timing
- Clearing cache blindly without request context
- Relying on server restart to clear cache
Ready to prove it?
Pass the test and this pattern moves unknown
