{"id":17493,"library":"apicache","title":"API Response Caching Middleware for Express/Node","description":"apicache is an ultra-simplified middleware for Express.js and Node.js designed to cache API responses. It supports both an in-memory store and Redis as a backend, allowing developers to define cache durations using plain-english strings (e.g., '5 minutes'). The current stable version is 1.6.3, with version 1.0.0 marking a production-ready release after extensive use. The project appears to have a moderate release cadence, focusing on stability and adding features incrementally, such as `res.write` support and official `compression` integration. Its key differentiator is its ease of use and 'automagic' caching injection into routes, making it a straightforward choice for basic API caching needs compared to more complex caching solutions.","status":"active","version":"1.6.3","language":"javascript","source_language":"en","source_url":"https://github.com/kwhitley/apicache","tags":["javascript","cache","API","redis","memcache","response","express","JSON","duration"],"install":[{"cmd":"npm install apicache","lang":"bash","label":"npm"},{"cmd":"yarn add apicache","lang":"bash","label":"yarn"},{"cmd":"pnpm add apicache","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Optional dependency for using Redis as the cache store instead of the default in-memory store.","package":"redis","optional":true},{"reason":"Optional dependency for caching gzip-compressed responses; apicache provides official support for it.","package":"compression","optional":true}],"imports":[{"note":"The default export is the main `apicache` object, which contains `middleware`, `options`, `getPerformance`, etc.","wrong":"const apicache = require('apicache').apicache","symbol":"apicache","correct":"import apicache from 'apicache'"},{"note":"`middleware` is a property of the default `apicache` object, not a named export. Ensure you import the default first.","wrong":"import { middleware } from 'apicache'","symbol":"middleware","correct":"import apicache from 'apicache'; let cache = apicache.middleware;"},{"note":"`options` is a method of the default `apicache` object, used for global configuration, not a named export.","wrong":"import { options } from 'apicache'","symbol":"options","correct":"import apicache from 'apicache'; apicache.options({ ... })"},{"note":"`clear` is a method of the default `apicache` object for manually invalidating cache entries or groups.","wrong":"import { clear } from 'apicache'","symbol":"clear","correct":"import apicache from 'apicache'; apicache.clear('target')"}],"quickstart":{"code":"import express from 'express';\nimport apicache from 'apicache';\nimport redis from 'redis'; // Optional: for Redis integration\n\nconst app = express();\n\n// --- Configuration for in-memory cache ---\nlet cache = apicache.middleware;\n\n// --- Configuration for Redis cache (uncomment to use) ---\n// const redisClient = redis.createClient({ url: process.env.REDIS_URL ?? 'redis://localhost:6379' });\n// redisClient.on('error', (err) => console.error('Redis Client Error', err));\n// redisClient.connect(); // Connect the client\n// let cache = apicache.options({ redisClient }).middleware;\n\n// Basic cached route (in-memory or Redis based on config above)\napp.get('/api/data', cache('1 minute'), (req, res) => {\n  console.log('Fetching fresh data for /api/data');\n  res.json({ timestamp: new Date(), value: Math.random() });\n});\n\n// Route to check cache performance and index\napp.get('/api/cache/performance', (req, res) => {\n  res.json(apicache.getPerformance());\n});\n\napp.get('/api/cache/index', (req, res) => {\n  res.json(apicache.getIndex());\n});\n\n// Route to manually clear cache (e.g., all entries, or a specific target/group)\napp.get('/api/cache/clear/:target?', (req, res) => {\n  const target = req.params.target || 'all'; // 'all' clears everything if no target is specified\n  console.log(`Clearing cache for target: ${target}`);\n  res.json(apicache.clear(target));\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log('Try visiting http://localhost:3000/api/data multiple times quickly.');\n  console.log('Then try http://localhost:3000/api/cache/clear');\n});\n","lang":"javascript","description":"This example sets up an Express server with `apicache` configured for either in-memory or Redis caching. It demonstrates how to apply caching middleware to a route, retrieve cache performance metrics, view the cache index, and manually clear cached entries by target or group."},"warnings":[{"fix":"Ensure `app.use(compression());` comes before `app.use(apicache.middleware('duration'));` or before any route-specific cache middleware.","message":"When using `apicache` with the `compression` middleware, ensure `compression` is applied *before* `apicache` in the middleware chain for `apicache` to cache the compressed response. Older versions might have had issues with header mutation, but v0.8.0 and later addressed this.","severity":"gotcha","affected_versions":"<0.8.0"},{"fix":"Adjust any custom middleware that relies on `apicache` headers to check for their presence during the response phase, specifically when a cache hit occurs.","message":"The injection of `apicache-store` and `apicache-version` headers moved from before cache-injection to response-building from cache. This means middleware interceptors will only detect these headers when a response is actually served from the cache, not when the request is initially processed.","severity":"breaking","affected_versions":">=0.7.1"},{"fix":"For detailed logging, set the environment variable `export DEBUG=apicache` before running your Node.js application instead of relying solely on `options({ debug: true })`.","message":"Debugging output for apicache, while configurable via `apicache.options({ debug: true })`, is now primarily and preferentially controlled via the `DEBUG` environment variable, specifically `DEBUG=apicache`.","severity":"gotcha","affected_versions":">=0.2.0"},{"fix":"Upgrade your Node.js environment to version 8 or newer.","message":"apicache requires Node.js version 8 or higher. Using it with older Node.js versions will lead to compatibility issues or failures.","severity":"breaking","affected_versions":"<8.0.0"},{"fix":"Set global options before creating or using the `middleware` instance: `let cache = apicache.options({ /* ... */ }).middleware;`","message":"When using `apicache.options()` to configure global settings (like `redisClient` or custom `headers`), ensure you apply it before initializing your `apicache.middleware`. Calling `options` modifies the global `apicache` object.","severity":"gotcha","affected_versions":">=0.0.1"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure you are importing the default `apicache` object: `import apicache from 'apicache';` and then accessing `middleware` as a property: `let cache = apicache.middleware;`","cause":"Incorrect import pattern, attempting to destructure `middleware` from `apicache` directly, or not importing `apicache` at all.","error":"TypeError: apicache.middleware is not a function"},{"fix":"Start your Redis server, verify its configuration (host/port), and ensure your application has network access to it. If using a custom URL, ensure `redis.createClient({ url: '...' })` is correct.","cause":"The Redis server is not running or is not accessible at the specified host and port.","error":"Error: Redis connection to localhost:6379 failed - connect ECONNREFUSED"},{"fix":"Replace `const apicache = require('apicache');` with `import apicache from 'apicache';`","cause":"Attempting to use CommonJS `require()` syntax in an ES Module (`.mjs` file or `type: \"module\"` in `package.json`) environment.","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Verify the target string passed to `apicache.clear(target)` matches an exact URL path or a `req.apicacheGroup` name. Use `apicache.getIndex()` to inspect current cached entries and groups to ensure correct targeting.","cause":"Incorrect `apicache.clear()` target, or misunderstanding of cache grouping.","error":"Cache is not clearing/invalidating as expected."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}