{"id":17608,"library":"express-cache-middleware","title":"Express Cache Middleware","description":"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.","status":"abandoned","version":"1.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/tprobinson/express-cache-middleware","tags":["javascript","express","middleware","cache","caching","cache-manager","mung","munge","intercept"],"install":[{"cmd":"npm install express-cache-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add express-cache-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add express-cache-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for the caching backend. This middleware is only compatible with cache-manager@2.x. Later versions introduce breaking changes.","package":"cache-manager","optional":false}],"imports":[{"note":"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.","wrong":"import ExpressCache from 'express-cache-middleware';","symbol":"ExpressCache","correct":"const ExpressCache = require('express-cache-middleware');"}],"quickstart":{"code":"const express = require('express');\nconst ExpressCache = require('express-cache-middleware');\nconst cacheManager = require('cache-manager');\n\nconst app = express();\n\n// Initialize cache-manager with a memory store (compatible with v2.x)\nconst memoryCache = cacheManager.caching({\n\tstore: 'memory', max: 10000, ttl: 3600 // 1 hour TTL\n});\n\nconst cacheMiddleware = new ExpressCache(memoryCache, {\n\t// Optional: Customize cache key based on request URL and specific query params\n\tgetCacheKey: (req) => {\n\t\tconst url = new URL(req.url, `http://${req.headers.host}`);\n\t\t// Remove 'timestamp' query param from cache key to ensure consistent caching\n\t\turl.searchParams.delete('timestamp');\n\t\treturn url.toString();\n\t}\n});\n\n// Layer the caching in front of the routes to be cached\ncacheMiddleware.attach(app);\n\n// Attach routes to be cached. This example caches all GET requests.\napp.get('/data', (req, res) => {\n\tconsole.log('Fetching data...');\n\t// Simulate an expensive operation or a database call\n\tsetTimeout(() => {\n\t\tres.status(200).send(`Data from server at ${new Date().toISOString()}`);\n\t}, 500);\n});\n\napp.get('/image', (req, res) => {\n\tconsole.log('Sending image...');\n\tres.set('Content-Type', 'image/png');\n\t// Simulate sending an image buffer\n\tres.send(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])); // A minimal PNG header\n});\n\nconst PORT = 3000;\napp.listen(PORT, () => {\n\tconsole.log(`Server listening on port ${PORT}`);\n\tconsole.log('Try visiting http://localhost:3000/data multiple times, then http://localhost:3000/data?timestamp=123');\n});","lang":"javascript","description":"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."},"warnings":[{"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.","message":"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`.","severity":"breaking","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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).","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Downgrade your `cache-manager` dependency to version `2.x`. For example, `npm uninstall cache-manager` then `npm install cache-manager@^2`.","cause":"You are likely using a version of `cache-manager` incompatible with `express-cache-middleware` (e.g., `cache-manager@3.x` or later).","error":"TypeError: cacheManager.caching is not a function"},{"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.","cause":"The `hydrate` option is not configured, causing the cached data to be streamed directly without setting appropriate `Content-Type` headers.","error":"Browser downloads file with 'application/octet-stream' instead of displaying content"},{"fix":"Provide a custom `getCacheKey` function that normalizes the request URL by removing or ignoring query parameters that should not differentiate cache entries.","cause":"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.","error":"Cache does not seem to work for requests with slightly different query parameters"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}