Cache middleware helps store data temporarily to make your app faster. It saves repeated work by remembering answers.
Cache middleware pattern in Express
const cache = new Map();
function cacheMiddleware(req, res, next) {
const key = req.originalUrl;
const cachedData = cache.get(key);
if (cachedData) {
res.send(cachedData);
} else {
res.sendResponse = res.send;
res.send = (body) => {
cache.set(key, body);
res.sendResponse(body);
};
next();
}
}The middleware checks if data for the request URL is in cache.
If cached, it sends the data immediately. Otherwise, it lets the request continue and saves the response.
const cache = new Map();
function cacheMiddleware(req, res, next) {
const key = req.originalUrl;
if (cache.has(key)) {
res.send(cache.get(key));
} else {
res.sendResponse = res.send;
res.send = (body) => {
cache.set(key, body);
res.sendResponse(body);
};
next();
}
}const cache = new Map();
function cacheMiddleware(duration) {
return (req, res, next) => {
const key = req.originalUrl;
if (cache.has(key)) {
res.send(cache.get(key));
} else {
res.sendResponse = res.send;
res.send = (body) => {
cache.set(key, body);
setTimeout(() => cache.delete(key), duration);
res.sendResponse(body);
};
next();
}
};
}This Express app uses cache middleware to save and reuse the response for the '/time' route. The first request shows the current time and caches it. Later requests return the cached time instantly.
import express from 'express'; const app = express(); const cache = new Map(); function cacheMiddleware(req, res, next) { const key = req.originalUrl; if (cache.has(key)) { console.log('Serving from cache:', key); res.send(cache.get(key)); } else { res.sendResponse = res.send; res.send = (body) => { cache.set(key, body); console.log('Caching response for:', key); res.sendResponse(body); }; next(); } } app.use(cacheMiddleware); app.get('/time', (req, res) => { const currentTime = new Date().toISOString(); res.send(`Current time is: ${currentTime}`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Cache middleware improves speed but may serve outdated data if cache is not cleared.
Use cache expiration or manual clearing to keep data fresh.
Cache keys should be unique per request to avoid wrong data delivery.
Cache middleware stores responses to speed up repeated requests.
It checks cache before processing and saves new responses after.
Use cache expiration to avoid stale data.
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
