Express Cache Middleware
raw JSON →Express Cache Middleware is an Express.js middleware designed to intercept HTTP responses and cache them, aiming to improve performance for repeated requests. Its current stable version is 1.0.1, last updated over seven years ago. The package operates by leveraging the `cache-manager` library for its caching backend, allowing for flexible storage options (e.g., memory, Redis, etc.) through `cache-manager`'s plugin system. A key differentiator is its backend-agnostic approach and the provision of customizable `getCacheKey` and `hydrate` options, enabling fine-grained control over cache key generation and transformation of cached data before it's sent to the client. However, due to its age, it is only compatible with `cache-manager` version 2.x, which is now deprecated, making it incompatible with modern `cache-manager` versions (3.x and above) and thus challenging to integrate into contemporary projects.
Common errors
error TypeError: cacheManager.caching is not a function ↓
cache-manager dependency to version 2.x. For example, npm uninstall cache-manager then npm install cache-manager@^2. error Browser downloads file with 'application/octet-stream' instead of displaying content ↓
hydrate function in your ExpressCache configuration to explicitly set the res.set('Content-Type', '...') header based on the cached data's type. This function runs before the cached content is sent back. error Cache does not seem to work for requests with slightly different query parameters ↓
getCacheKey function that normalizes the request URL by removing or ignoring query parameters that should not differentiate cache entries. Warnings
breaking This package is only compatible with `cache-manager@2.x`. It will not work out-of-the-box with `cache-manager@3.x` or later versions due to significant API changes in `cache-manager`. ↓
gotcha By default, cached responses are streamed as `application/octet-stream` if not explicitly handled. This is often not the desired `Content-Type` for common web content like HTML, JSON, or images. ↓
gotcha The default cache key is the request URL. This can lead to inefficient caching or cache misses if URLs vary with irrelevant query parameters (e.g., tracking IDs, timestamps). ↓
Install
npm install express-cache-middleware yarn add express-cache-middleware pnpm add express-cache-middleware Imports
- ExpressCache wrong
import ExpressCache from 'express-cache-middleware';correctconst ExpressCache = require('express-cache-middleware');
Quickstart
const express = require('express');
const ExpressCache = require('express-cache-middleware');
const cacheManager = require('cache-manager');
const app = express();
// Initialize cache-manager with a memory store (compatible with v2.x)
const memoryCache = cacheManager.caching({
store: 'memory', max: 10000, ttl: 3600 // 1 hour TTL
});
const cacheMiddleware = new ExpressCache(memoryCache, {
// Optional: Customize cache key based on request URL and specific query params
getCacheKey: (req) => {
const url = new URL(req.url, `http://${req.headers.host}`);
// Remove 'timestamp' query param from cache key to ensure consistent caching
url.searchParams.delete('timestamp');
return url.toString();
}
});
// Layer the caching in front of the routes to be cached
cacheMiddleware.attach(app);
// Attach routes to be cached. This example caches all GET requests.
app.get('/data', (req, res) => {
console.log('Fetching data...');
// Simulate an expensive operation or a database call
setTimeout(() => {
res.status(200).send(`Data from server at ${new Date().toISOString()}`);
}, 500);
});
app.get('/image', (req, res) => {
console.log('Sending image...');
res.set('Content-Type', 'image/png');
// Simulate sending an image buffer
res.send(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])); // A minimal PNG header
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
console.log('Try visiting http://localhost:3000/data multiple times, then http://localhost:3000/data?timestamp=123');
});