Course contentsShow
← Node.js
Lesson 643 of 1,9807. Web Framework Architecture and MiddlewareFree lesson

Caching Strategies for Middleware

Use memory stores to cache repetitive request responses to reduce database load.

In this lesson, you will learn how to implement an in-memory cache within your middleware chain to serve repetitive request responses without hitting your database.

Why Cache in Middleware?

In a Stateless Server Architecture, every request typically triggers a fresh query to your database. If you have an endpoint that returns frequently accessed data—like a list of categories or site settings—your database will perform the same work thousands of times. By introducing a cache layer directly into your middleware pipeline, you can intercept these requests, return the cached result immediately, and spare your database the unnecessary load.

Implementing a Simple Memory Store

To implement this, we use a simple JavaScript object to store our responses in memory. The middleware checks if a key exists; if it does, it sends the response. If not, it allows the request to proceed to the database, then saves the result before sending it to the client.

const cache = {};

const cacheMiddleware = (req, res, next) => {
  const key = req.originalUrl;

  // Check if response exists in memory
  if (cache[key]) {
    return res.json(cache[key]);
  }

  // Override res.json to capture the data before sending it
  const originalJson = res.json;
  res.json = (body) => {
    cache[key] = body; // Save to memory store
    originalJson.call(res, body);
  };

  next();
};

Considerations for Middleware Caching

When caching in memory, keep two things in mind:

  1. Memory Growth: Storing everything in an object will consume your server's RAM over time. In a real-world scenario, you would implement an expiration policy or a size limit to prevent memory leaks.
  2. Stale Data: Since this cache lives inside your application process, it does not automatically know when the underlying database has changed. You must implement logic to invalidate or clear the cache when your data is updated.

By placing this logic early in your Middleware Sequencing, you create a "short-circuit" that significantly reduces response times and database pressure.

Key Takeaway: Middleware caching acts as a protective layer that intercepts repetitive read-heavy requests, serving them directly from memory to minimize expensive database operations.