Registry / web-framework / express-cache-middleware

express-cache-middleware

JSON →
library1.0.1jsnpmunverified

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.

npm install express-cache-middleware
INSTALL
IMPORT
SIG · EXPRESS-CACHE-MIDD
E
express-cache-middleware
web-frameworkjavascriptv1.0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ExpressCache
const ExpressCache = require('express-cache-middleware');
import ExpressCache from 'express-cache-middleware';
This package is a CommonJS module. Direct ESM `import` statements may require specific build configurations like `esModuleInterop: true` in TypeScript, or could lead to unexpected behavior in pure ESM environments.

Demonstrates the basic setup of Express Cache Middleware with an in-memory cache-manager, including a custom `getCacheKey` function, and attaches it to an Express app to cache responses from sample routes.

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'); });
Debug
Known issues
breakingThis 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`.
fix
You must explicitly install `cache-manager@2.x` (e.g., `npm install cache-manager@^2`) or use an alternative, more modern caching middleware for Express.
affects: >=1.0.0
gotchaBy 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.
fix
Implement the `hydrate` option in the middleware configuration. This function allows you to set appropriate `Content-Type` headers and perform any necessary data transformations (e.g., parsing JSON or decompressing data) before the cached response is sent to the client. Remember `hydrate` is only called on cache hits.
affects: >=1.0.0
gotchaThe 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).
fix
Provide a custom `getCacheKey` function in the middleware options. This function receives the Express request object and should return a unique string key. Customize it to ignore irrelevant parts of the URL or request to ensure consistent caching for logically identical requests.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: cacheManager.caching is not a function
You are likely using a version of `cache-manager` incompatible with `express-cache-middleware` (e.g., `cache-manager@3.x` or later).
fix
Downgrade your `cache-manager` dependency to version `2.x`. For example, `npm uninstall cache-manager` then `npm install cache-manager@^2`.
Browser downloads file with 'application/octet-stream' instead of displaying content
The `hydrate` option is not configured, causing the cached data to be streamed directly without setting appropriate `Content-Type` headers.
fix
Implement the `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.
Cache does not seem to work for requests with slightly different query parameters
The default `getCacheKey` uses the full request URL, meaning a URL with `?param=1` and `?param=2` will generate two distinct cache entries, even if the difference is irrelevant to the cached content.
fix
Provide a custom `getCacheKey` function that normalizes the request URL by removing or ignoring query parameters that should not differentiate cache entries.
Upgrade
Version history
1.0.1latest on npm
Audit
Dependencies
cache-managerrequiredRequired for the caching backend. This middleware is only compatible with cache-manager@2.x. Later versions introduce breaking changes.
Agent activity
16 hits · last 30 days
node
14
OpenAI (training)
2
Resources
express-cache-middleware — npm install express-cache-middleware · libregistry