0
0
Expressframework~5 mins

Cache middleware pattern in Express

Choose your learning style9 modes available
Introduction

Cache middleware helps store data temporarily to make your app faster. It saves repeated work by remembering answers.

When your app fetches the same data many times quickly.
When you want to reduce slow database or API calls.
When you want to improve user experience by loading pages faster.
When you want to save server resources by avoiding repeated processing.
Syntax
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.

Examples
Simple cache using a Map to store responses by URL.
Express
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();
  }
}
Cache middleware with expiration time to clear old cache after given duration.
Express
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();
    }
  };
}
Sample Program

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.

Express
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');
});
OutputSuccess
Important Notes

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.

Summary

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.