These six packages offer different approaches to caching in Node.js environments, ranging from simple in-memory storage to HTTP-specific caching layers. lru-cache provides a fundamental Least Recently Used algorithm implementation, while node-cache and memory-cache offer straightforward in-memory key-value storage with TTL support. cache-manager acts as a wrapper allowing multiple cache stores (memory, Redis, etc.) with a unified API. apicache focuses specifically on Express middleware for caching HTTP responses, and cacheable-request adds HTTP caching semantics to request clients. Each serves distinct architectural needs from low-level data structures to high-level HTTP response caching.
Caching is essential for building performant Node.js applications, but picking the wrong tool can lead to memory leaks, stale data, or unnecessary complexity. The six packages we are comparing — apicache, cache-manager, cacheable-request, lru-cache, memory-cache, and node-cache — each solve different parts of the caching puzzle. Some focus on HTTP responses, others on data structures, and some on abstraction layers. Let's break down how they work and when to use each one.
lru-cache is a pure data structure implementation.
// lru-cache: Basic usage
import { LRUCache } from 'lru-cache';
const cache = new LRUCache({
max: 500,
ttl: 1000 * 60 * 5 // 5 minutes
});
cache.set('key', 'value');
const value = cache.get('key');
node-cache is a full in-memory cache with TTL and events.
// node-cache: With TTL and events
import NodeCache from 'node-cache';
const cache = new NodeCache({ stdTTL: 100 });
cache.on('expired', (key, value) => {
console.log(`Key ${key} expired`);
});
cache.set('key', 'value', 200);
const value = cache.get('key');
memory-cache is a minimal in-memory store.
// memory-cache: Simple set/get
import cache from 'memory-cache';
cache.put('key', 'value', 1000 * 60); // 1 minute
const value = cache.get('key');
cache.del('key');
cache-manager is an abstraction layer over multiple stores.
// cache-manager: With memory store
import cacheManager from 'cache-manager';
import memoryStore from 'cache-manager-remember';
const cache = cacheManager.caching({
store: memoryStore,
ttl: 60,
max: 100
});
await cache.set('key', 'value');
const value = await cache.get('key');
apicache is Express middleware for HTTP response caching.
// apicache: Express middleware
import apicache from 'apicache';
import express from 'express';
const app = express();
app.use(apicache.middleware);
app.get('/api/data', apicache.middleware('5 minutes'), (req, res) => {
res.json({ data: 'cached response' });
});
cacheable-request adds HTTP caching to request clients.
got, request, or native http.// cacheable-request: HTTP caching
import CacheableRequest from 'cacheable-request';
import http from 'http';
const cacheableRequest = new CacheableRequest(http.request);
const req = cacheableRequest('https://api.example.com/data', {
cacheOptions: { cacheTtl: 1000 * 60 * 5 }
});
req.on('response', (res) => {
console.log('Status:', res.statusCode);
});
How each package handles time-based expiration varies significantly.
lru-cache uses TTL per entry in newer versions (v7+). Older versions relied on LRU eviction only.node-cache has global and per-key TTL with automatic cleanup intervals.memory-cache supports per-key TTL but no global cleanup configuration.cache-manager delegates TTL to the underlying store implementation.apicache uses TTL for HTTP response validity.cacheable-request respects HTTP Cache-Control headers plus optional overrides.// lru-cache: Per-entry TTL
const cache = new LRUCache({ ttl: 5000 });
cache.set('key', 'value', 5000); // 5 seconds
// node-cache: Global and per-key TTL
const cache = new NodeCache({ stdTTL: 60 });
cache.set('key', 'value', 120); // Overrides global to 2 minutes
// memory-cache: Per-key TTL only
cache.put('key', 'value', 60000); // 60 seconds
// cache-manager: Store-dependent TTL
await cache.set('key', 'value', 60); // 60 seconds
// apicache: Middleware TTL string
app.get('/api', apicache.middleware('10 minutes'), handler);
// cacheable-request: HTTP header based
const req = cacheableRequest(url, { cacheOptions: { cacheTtl: 60000 } });
Understanding how items leave the cache is critical for memory management.
lru-cache evicts based on access order when max size is reached. Least recently used items go first.node-cache evicts based on TTL expiration with periodic cleanup checks.memory-cache evicts based on TTL expiration during get operations.cache-manager depends on the store — memory uses LRU or TTL, Redis uses TTL.apicache evicts based on TTL and memory limits.cacheable-request evicts based on HTTP cache headers and storage limits.// lru-cache: LRU eviction when max reached
const cache = new LRUCache({ max: 100 });
// When 101st item added, oldest accessed item is removed
// node-cache: TTL-based cleanup
const cache = new NodeCache({ checkperiod: 60 }); // Check every 60 seconds
// memory-cache: Lazy cleanup on get
// Items removed when accessed after expiration
// cache-manager: Configurable per store
const cache = cacheManager.caching({ store: 'memory', max: 100 });
// apicache: Memory limit configuration
apicache.options({ debug: true, defaultDuration: 3600000 });
// cacheable-request: Storage-based eviction
const cacheableRequest = new CacheableRequest(http.request, { cacheAdapter: new Keyv() });
Some packages cache HTTP responses, others cache application data.
apicache and cacheable-request focus on HTTP layer caching.lru-cache, node-cache, memory-cache, and cache-manager focus on application data.// apicache: HTTP response caching
app.get('/users', apicache.middleware('5 minutes'), getUsers);
// cacheable-request: HTTP client caching
const getData = () => cacheableRequest('https://api.example.com/users');
// node-cache: Application data caching
const users = await cache.get('users');
if (!users) {
const data = await db.query('SELECT * FROM users');
cache.set('users', data);
}
// lru-cache: Application data with LRU
const cache = new LRUCache({ max: 1000 });
cache.set('userId', userData);
// memory-cache: Simple data caching
cache.put('session', sessionData, 3600000);
// cache-manager: Unified data caching
await cache.set('config', configData, 300);
Not all packages are equally maintained for production use.
apicache — ⚠️ No longer actively maintained. Last significant update was in 2021. Consider alternatives like route-cache or custom middleware for new projects.memory-cache — ⚠️ Minimal maintenance. Works but lacks modern features and active development.lru-cache — ✅ Actively maintained. Widely used as a dependency by many major packages.node-cache — ✅ Stable and maintained. Good for in-process caching needs.cache-manager — ✅ Actively maintained. Regular updates and community support.cacheable-request — ✅ Maintained. Works well with modern HTTP clients.// For new projects, prefer maintained packages
import { LRUCache } from 'lru-cache'; // ✅ Recommended
import NodeCache from 'node-cache'; // ✅ Recommended
import cacheManager from 'cache-manager'; // ✅ Recommended
// Avoid for new production projects
import apicache from 'apicache'; // ⚠️ Deprecated
import cache from 'memory-cache'; // ⚠️ Minimal maintenance
| Feature | lru-cache | node-cache | memory-cache | cache-manager | apicache | cacheable-request |
|---|---|---|---|---|---|---|
| Type | Data Structure | In-Memory Cache | In-Memory Cache | Cache Abstraction | HTTP Middleware | HTTP Client Wrapper |
| TTL Support | ✅ (v7+) | ✅ | ✅ | ✅ (Store-dependent) | ✅ | ✅ (HTTP Headers) |
| LRU Eviction | ✅ | ❌ | ❌ | ✅ (Memory store) | ✅ | ❌ |
| Events/Hooks | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ |
| Multi-Store | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ |
| HTTP Aware | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |
| Maintenance | ✅ Active | ✅ Stable | ⚠️ Minimal | ✅ Active | ⚠️ Deprecated | ✅ Active |
| Best For | Low-level caching | In-process data | Simple prototyping | Flexible backends | Express response caching | External API calls |
You need to cache query results in memory with automatic expiration.
node-cache or lru-cache// Using node-cache for query results
const cache = new NodeCache({ stdTTL: 300 });
async function getUser(id) {
const cached = cache.get(`user:${id}`);
if (cached) return cached;
const user = await db.users.findById(id);
cache.set(`user:${id}`, user);
return user;
}
You make frequent calls to third-party APIs and want to respect their cache headers.
cacheable-request// Using cacheable-request for external APIs
const cacheableRequest = new CacheableRequest(http.request);
async function fetchExternalData(url) {
return new Promise((resolve, reject) => {
const req = cacheableRequest(url);
req.on('response', res => {
// Handle response with caching applied
});
req.end();
});
}
You want to cache entire HTTP responses for GET endpoints.
cache-manager with Expressapicache is deprecated. Build custom logic or use maintained alternatives.// Custom Express caching with cache-manager
app.get('/api/data', async (req, res) => {
const cached = await cache.get(req.url);
if (cached) return res.json(cached);
const data = await fetchData();
await cache.set(req.url, data, 60);
res.json(data);
});
You need to switch between memory (development) and Redis (production) without code changes.
cache-manager// cache-manager with configurable store
const store = process.env.NODE_ENV === 'production' ? 'redis' : 'memory';
const cache = cacheManager.caching({
store: store,
ttl: 60,
redis: { host: 'localhost', port: 6379 }
});
You need maximum performance for a hot path with strict memory limits.
lru-cache// lru-cache for performance-critical paths
const cache = new LRUCache({
max: 10000,
ttl: 60000,
updateAgeOnGet: true
});
For most applications, start with node-cache for simple in-memory needs or cache-manager if you anticipate needing Redis later. Both are well-maintained and offer good developer experience.
For HTTP-specific caching, use cacheable-request for external API calls. Avoid apicache in new projects due to its deprecated status — instead, build custom Express middleware using cache-manager or a Redis-backed solution.
For low-level optimization, lru-cache is the gold standard. It is used by many major packages internally and provides the best performance for LRU-based eviction.
Avoid memory-cache for production systems requiring long-term support. While simple, it lacks the features and maintenance commitment of node-cache or cache-manager.
Remember that caching adds complexity — always measure the performance impact and ensure your cache invalidation strategy matches your data consistency requirements. A well-configured cache can speed up your application significantly, but a poorly managed one can lead to stale data and hard-to-debug issues.
Choose apicache if you need quick HTTP response caching for Express applications without writing custom logic. It works as middleware to cache entire route responses based on status codes and TTL. However, note that this package is no longer actively maintained, so evaluate newer alternatives for production systems requiring long-term support.
Choose cache-manager when you need flexibility to swap cache backends (memory, Redis, file system) without changing your application code. It provides a unified API across different stores and supports clustering. Ideal for applications that might need to scale from simple in-memory caching to distributed Redis caching later.
Choose cacheable-request when you need HTTP-level caching that respects standard cache headers (ETag, Last-Modified, Cache-Control). It wraps HTTP clients like got or request to automatically handle caching based on server responses. Best for applications making many external API calls where you want to respect upstream cache policies.
Choose lru-cache when you need a performant, low-level LRU data structure without extra features like TTL or clustering. It is highly optimized and widely used as a dependency by other caching libraries. Perfect for scenarios where you need fine-grained control over cache eviction based on access patterns rather than time.
Choose memory-cache for simple, lightweight in-memory caching with basic TTL support in small Node.js applications. It has a very simple API but lacks advanced features like clustering or multiple stores. Consider this only for development or small-scale projects where complexity must be minimized.
Choose node-cache when you need a reliable in-memory cache with TTL, event hooks, and key pattern matching in a single Node.js process. It offers more features than memory-cache while remaining simple to use. Suitable for applications that need periodic cleanup and cache event monitoring without external dependencies.
Because route-caching of simple data/responses should ALSO be simple.
To use, simply inject the middleware (example: apicache.middleware('5 minutes', [optionalMiddlewareToggle])) into your routes. Everything else is automagic.
import express from 'express'
import apicache from 'apicache'
let app = express()
let cache = apicache.middleware
app.get('/api/collection/:id?', cache('5 minutes'), (req, res) => {
// do some work... this will only occur once per 5 minutes
res.json({ foo: 'bar' })
})
let cache = apicache.middleware
app.use(cache('5 minutes'))
app.get('/will-be-cached', (req, res) => {
res.json({ success: true })
})
import express from 'express'
import apicache from 'apicache'
import redis from 'redis'
let app = express()
// if redisClient option is defined, apicache will use redis client
// instead of built-in memory store
let cacheWithRedis = apicache.options({ redisClient: redis.createClient() }).middleware
app.get('/will-be-cached', cacheWithRedis('5 minutes'), (req, res) => {
res.json({ success: true })
})
import apicache from 'apicache'
let cache = apicache.middleware
app.use(cache('5 minutes'))
// routes are automatically added to index, but may be further added
// to groups for quick deleting of collections
app.get('/api/:collection/:item?', (req, res) => {
req.apicacheGroup = req.params.collection
res.json({ success: true })
})
// add route to display cache performance (courtesy of @killdash9)
app.get('/api/cache/performance', (req, res) => {
res.json(apicache.getPerformance())
})
// add route to display cache index
app.get('/api/cache/index', (req, res) => {
res.json(apicache.getIndex())
})
// add route to manually clear target/group
app.get('/api/cache/clear/:target?', (req, res) => {
res.json(apicache.clear(req.params.target))
})
/*
GET /api/foo/bar --> caches entry at /api/foo/bar and adds a group called 'foo' to index
GET /api/cache/index --> displays index
GET /api/cache/clear/foo --> clears all cached entries for 'foo' group/collection
*/
// higher-order function returns false for responses of other status codes (e.g. 403, 404, 500, etc)
const onlyStatus200 = (req, res) => res.statusCode === 200
const cacheSuccesses = cache('5 minutes', onlyStatus200)
app.get('/api/missing', cacheSuccesses, (req, res) => {
res.status(404).json({ results: 'will not be cached' })
})
app.get('/api/found', cacheSuccesses, (req, res) => {
res.json({ results: 'will be cached' })
})
let cache = apicache.options({
headers: {
'cache-control': 'no-cache',
},
}).middleware
let cache5min = cache('5 minute') // continue to use normally
apicache.options([globalOptions]) - getter/setter for global options. If used as a setter, this function is chainable, allowing you to do things such as... say... return the middleware.apicache.middleware([duration], [toggleMiddleware], [localOptions]) - the actual middleware that will be used in your routes. duration is in the following format "[length][unit]", as in "10 minutes" or "1 day". A second param is a middleware toggle function, accepting request and response params, and must return truthy to enable cache for the request. Third param is the options that will override global ones and affect this middleware only.middleware.options([localOptions]) - getter/setter for middleware-specific options that will override global ones.apicache.getPerformance() - returns current cache performance (cache hit rate)apicache.getIndex() - returns current cache index [of keys]apicache.clear([target]) - clears cache target (key or group), or entire cache if no value passed, returns new index.apicache.newInstance([options]) - used to create a new ApiCache instance (by default, simply requiring this library shares a common instance)apicache.clone() - used to create a new ApiCache instance with the same options as the current one{
debug: false|true, // if true, enables console output
defaultDuration: '1 hour', // should be either a number (in ms) or a string, defaults to 1 hour
enabled: true|false, // if false, turns off caching globally (useful on dev)
redisClient: client, // if provided, uses the [node-redis](https://github.com/NodeRedis/node_redis) client instead of [memory-cache](https://github.com/ptarjan/node-cache)
appendKey: fn(req, res), // appendKey takes the req/res objects and returns a custom value to extend the cache key
headerBlacklist: [], // list of headers that should never be cached
statusCodes: {
exclude: [], // list status codes to specifically exclude (e.g. [404, 403] cache all responses unless they had a 404 or 403 status)
include: [], // list status codes to require (e.g. [200] caches ONLY responses with a success/200 code)
},
trackPerformance: false, // enable/disable performance tracking... WARNING: super cool feature, but may cause memory overhead issues
headers: {
// 'cache-control': 'no-cache' // example of header overwrite
},
respectCacheControl: false|true // If true, 'Cache-Control: no-cache' in the request header will bypass the cache.
}
$ npm install -D @types/apicache
Sometimes you need custom keys (e.g. save routes per-session, or per method). We've made it easy!
Note: All req/res attributes used in the generation of the key must have been set previously (upstream). The entire route logic block is skipped on future cache hits so it can't rely on those params.
apicache.options({
appendKey: (req, res) => req.method + res.session.id,
})
Oftentimes it benefits us to group cache entries, for example, by collection (in an API). This
would enable us to clear all cached "post" requests if we updated something in the "post" collection
for instance. Adding a simple req.apicacheGroup = [somevalue]; to your route enables this. See example below:
var apicache = require('apicache')
var cache = apicache.middleware
// GET collection/id
app.get('/api/:collection/:id?', cache('1 hour'), function(req, res, next) {
req.apicacheGroup = req.params.collection
// do some work
res.send({ foo: 'bar' })
})
// POST collection/id
app.post('/api/:collection/:id?', function(req, res, next) {
// update model
apicache.clear(req.params.collection)
res.send('added a new item, so the cache has been cleared')
})
Additionally, you could add manual cache control to the previous project with routes such as these:
// GET apicache index (for the curious)
app.get('/api/cache/index', function(req, res, next) {
res.send(apicache.getIndex())
})
// GET apicache index (for the curious)
app.get('/api/cache/clear/:key?', function(req, res, next) {
res.send(200, apicache.clear(req.params.key || req.query.key))
})
$ export DEBUG=apicache
$ export DEBUG=apicache,othermoduleThatDebugModuleWillPickUp,etc
import apicache from 'apicache'
apicache.options({ debug: true })
When sharing GET routes between admin and public sites, you'll likely want the
routes to be cached from your public client, but NOT cached when from the admin client. This
is achieved by sending a "x-apicache-bypass": true header along with the requst from the admin.
The presence of this header flag will bypass the cache, ensuring you aren't looking at stale data.
Special thanks to all those that use this library and report issues, but especially to the following active users that have helped add to the core functionality!