Gathering detailed insights and metrics for apicache
Gathering detailed insights and metrics for apicache
Gathering detailed insights and metrics for apicache
Gathering detailed insights and metrics for apicache
apicache-plus
Effortless api response caching for Express/Node using plain-english durations
@types/apicache
TypeScript definitions for apicache
@pengqiangsheng/apicache
An ultra-simplified API response caching middleware for Koa using plain-english durations.
apicache-extra
An ultra-simplified API response caching middleware for Express/Node using plain-english durations.
npm install apicache
Typescript
Module System
Min. Node Version
Node Version
NPM Version
98.1
Supply Chain
99.6
Quality
81.1
Maintenance
100
Vulnerability
100
License
JavaScript (100%)
Total Downloads
9,362,837
Last Day
1,104
Last Week
30,293
Last Month
122,749
Last Year
1,604,578
MIT License
1,246 Stars
367 Commits
196 Forks
16 Watchers
21 Branches
30 Contributors
Updated on Jun 04, 2025
Minified
Minified + Gzipped
Latest Version
1.6.3
Package Id
apicache@1.6.3
Size
19.66 kB
NPM Version
7.0.15
Node Version
15.4.0
Published on
Oct 25, 2021
Cumulative downloads
Total Downloads
Last Day
2%
1,104
Compared to previous day
Last Week
-3%
30,293
Compared to previous week
Last Month
-0.6%
122,749
Compared to previous month
Last Year
7.3%
1,604,578
Compared to previous year
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.
1import express from 'express' 2import apicache from 'apicache' 3 4let app = express() 5let cache = apicache.middleware 6 7app.get('/api/collection/:id?', cache('5 minutes'), (req, res) => { 8 // do some work... this will only occur once per 5 minutes 9 res.json({ foo: 'bar' }) 10})
1let cache = apicache.middleware 2 3app.use(cache('5 minutes')) 4 5app.get('/will-be-cached', (req, res) => { 6 res.json({ success: true }) 7})
1import express from 'express' 2import apicache from 'apicache' 3import redis from 'redis' 4 5let app = express() 6 7// if redisClient option is defined, apicache will use redis client 8// instead of built-in memory store 9let cacheWithRedis = apicache.options({ redisClient: redis.createClient() }).middleware 10 11app.get('/will-be-cached', cacheWithRedis('5 minutes'), (req, res) => { 12 res.json({ success: true }) 13})
1import apicache from 'apicache' 2let cache = apicache.middleware 3 4app.use(cache('5 minutes')) 5 6// routes are automatically added to index, but may be further added 7// to groups for quick deleting of collections 8app.get('/api/:collection/:item?', (req, res) => { 9 req.apicacheGroup = req.params.collection 10 res.json({ success: true }) 11}) 12 13// add route to display cache performance (courtesy of @killdash9) 14app.get('/api/cache/performance', (req, res) => { 15 res.json(apicache.getPerformance()) 16}) 17 18// add route to display cache index 19app.get('/api/cache/index', (req, res) => { 20 res.json(apicache.getIndex()) 21}) 22 23// add route to manually clear target/group 24app.get('/api/cache/clear/:target?', (req, res) => { 25 res.json(apicache.clear(req.params.target)) 26}) 27 28/* 29 30GET /api/foo/bar --> caches entry at /api/foo/bar and adds a group called 'foo' to index 31GET /api/cache/index --> displays index 32GET /api/cache/clear/foo --> clears all cached entries for 'foo' group/collection 33 34*/
1// higher-order function returns false for responses of other status codes (e.g. 403, 404, 500, etc) 2const onlyStatus200 = (req, res) => res.statusCode === 200 3 4const cacheSuccesses = cache('5 minutes', onlyStatus200) 5 6app.get('/api/missing', cacheSuccesses, (req, res) => { 7 res.status(404).json({ results: 'will not be cached' }) 8}) 9 10app.get('/api/found', cacheSuccesses, (req, res) => { 11 res.json({ results: 'will be cached' }) 12})
1let cache = apicache.options({ 2 headers: { 3 'cache-control': 'no-cache', 4 }, 5}).middleware 6 7let 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 one1{ 2 debug: false|true, // if true, enables console output 3 defaultDuration: '1 hour', // should be either a number (in ms) or a string, defaults to 1 hour 4 enabled: true|false, // if false, turns off caching globally (useful on dev) 5 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) 6 appendKey: fn(req, res), // appendKey takes the req/res objects and returns a custom value to extend the cache key 7 headerBlacklist: [], // list of headers that should never be cached 8 statusCodes: { 9 exclude: [], // list status codes to specifically exclude (e.g. [404, 403] cache all responses unless they had a 404 or 403 status) 10 include: [], // list status codes to require (e.g. [200] caches ONLY responses with a success/200 code) 11 }, 12 trackPerformance: false, // enable/disable performance tracking... WARNING: super cool feature, but may cause memory overhead issues 13 headers: { 14 // 'cache-control': 'no-cache' // example of header overwrite 15 }, 16 respectCacheControl: false|true // If true, 'Cache-Control: no-cache' in the request header will bypass the cache. 17}
1$ 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.
1apicache.options({ 2 appendKey: (req, res) => req.method + res.session.id, 3})
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:
1var apicache = require('apicache') 2var cache = apicache.middleware 3 4// GET collection/id 5app.get('/api/:collection/:id?', cache('1 hour'), function(req, res, next) { 6 req.apicacheGroup = req.params.collection 7 // do some work 8 res.send({ foo: 'bar' }) 9}) 10 11// POST collection/id 12app.post('/api/:collection/:id?', function(req, res, next) { 13 // update model 14 apicache.clear(req.params.collection) 15 res.send('added a new item, so the cache has been cleared') 16})
Additionally, you could add manual cache control to the previous project with routes such as these:
1// GET apicache index (for the curious) 2app.get('/api/cache/index', function(req, res, next) { 3 res.send(apicache.getIndex()) 4}) 5 6// GET apicache index (for the curious) 7app.get('/api/cache/clear/:key?', function(req, res, next) { 8 res.send(200, apicache.clear(req.params.key || req.query.key)) 9})
$ export DEBUG=apicache
$ export DEBUG=apicache,othermoduleThatDebugModuleWillPickUp,etc
1import apicache from 'apicache' 2 3apicache.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!
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 5/25 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
52 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-06-09
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More