0
0
Expressframework~10 mins

Cache middleware pattern in Express - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Cache middleware pattern
Incoming Request
Check Cache for Data
Return Cached Data
Send Response
Store Data in Cache
Send Response
The middleware checks if data is in cache. If yes, it returns cached data. If no, it fetches fresh data, stores it in cache, then sends response.
Execution Sample
Express
const cache = {};

function cacheMiddleware(req, res, next) {
  const key = req.url;
  if (cache[key]) {
    return res.send(cache[key]);
  }
  res.sendResponse = res.send.bind(res);
  res.send = (body) => {
    cache[key] = body;
    res.sendResponse(body);
  };
  next();
}
This middleware checks if the response for the request URL is cached. If yes, it sends cached data. Otherwise, it overrides res.send to cache the response before sending.
Execution Table
StepActionCache StateResponse SentNext Called
1Request arrives for /data{}NoYes
2Check cache for /data{}NoYes
3Cache miss, override res.send{}NoYes
4Call next middleware to fetch data{}NoYes
5Data fetched: 'Hello World'{}NoYes
6res.send('Hello World') called{'/data': 'Hello World'}YesNo
7Response sent with 'Hello World'{'/data': 'Hello World'}YesNo
8Next request arrives for /data{'/data': 'Hello World'}NoNo
9Check cache for /data{'/data': 'Hello World'}NoNo
10Cache hit, send cached response{'/data': 'Hello World'}YesNo
11Response sent with cached 'Hello World'{'/data': 'Hello World'}YesNo
💡 Execution stops after response is sent either from cache or fresh data.
Variable Tracker
VariableStartAfter Step 6After Step 10Final
cache{}{'/data': 'Hello World'}{'/data': 'Hello World'}{'/data': 'Hello World'}
res.sendResponseundefinedfunctionundefinedundefined
res.sendfunctionoverridden functionfunctionfunction
Key Moments - 3 Insights
Why do we override res.send inside the middleware?
We override res.send to capture the response body so we can store it in the cache before sending it to the client, as shown in step 6 of the execution_table.
What happens if the cache has the data?
If cache has data (cache hit), the middleware sends the cached response immediately without calling next(), as shown in steps 9 and 10.
Why do we call next() only on cache miss?
Calling next() passes control to the next middleware or handler to fetch fresh data only when cache misses, as shown in step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the cache content after step 6?
Aundefined
B{}
C{"/data": "Hello World"}
D{"/data": null}
💡 Hint
Check the 'Cache State' column at step 6 in the execution_table.
At which step does the middleware send cached data without calling next()?
AStep 4
BStep 10
CStep 3
DStep 1
💡 Hint
Look for 'Cache hit' and 'Next Called' = No in the execution_table.
If we remove the override of res.send, what will happen on cache miss?
AResponse will not be cached
BCache will store empty data
CMiddleware will send cached data anyway
DNext middleware will not be called
💡 Hint
Refer to how caching happens at step 6 by overriding res.send.
Concept Snapshot
Cache Middleware Pattern in Express:
- Middleware checks if response for req.url is cached.
- If cached, sends cached response immediately.
- If not, overrides res.send to cache response body.
- Calls next() to fetch fresh data.
- Stores fresh response in cache before sending.
- Improves performance by avoiding repeated data fetch.
Full Transcript
This visual execution trace shows how cache middleware works in Express. When a request arrives, the middleware checks if the response is already cached for the request URL. If yes, it sends the cached response immediately without calling the next middleware. If no, it overrides the res.send method to capture the response body when the next middleware sends it. Then it calls next() to fetch fresh data. When the response is sent, the overridden res.send caches the response body before sending it to the client. This process speeds up repeated requests by serving cached data quickly. The variable tracker shows how the cache object updates after the first response. Key moments clarify why res.send is overridden and when next() is called. The quiz tests understanding of cache state and middleware flow.