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-middlewareVerified import paths — ran on the pinned version, not inferred.
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.
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.
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.
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.
Downgrade your `cache-manager` dependency to version `2.x`. For example, `npm uninstall cache-manager` then `npm install cache-manager@^2`.
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.Provide a custom `getCacheKey` function that normalizes the request URL by removing or ignoring query parameters that should not differentiate cache entries.