A simple API response caching middleware for Express/Node using plain-english durations.

Supports Redis or built-in memory engine with auto-clearing.

Because route-caching of simple data/responses should ALSO be simple.

Usage

To use, simply inject the middleware (example: apicache.middleware('5 minutes', [optionalMiddlewareToggle]) ) into your routes. Everything else is automagic.

Cache a route

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 ) => { res . json ( { foo : ' bar ' } ) } )

Cache all routes

let cache = apicache . middleware app . use ( cache ( ' 5 minutes ' ) ) app . get ( ' /will-be-cached ' , ( req , res ) => { res . json ( { success : true } ) } )

Use with Redis

import express from ' express ' import apicache from ' apicache ' import redis from ' redis ' let app = express ( ) let cacheWithRedis = apicache . options ( { redisClient : redis . createClient ( ) } ) . middleware app . get ( ' /will-be-cached ' , cacheWithRedis ( ' 5 minutes ' ) , ( req , res ) => { res . json ( { success : true } ) } )

Cache grouping and manual controls

import apicache from ' apicache ' let cache = apicache . middleware app . use ( cache ( ' 5 minutes ' ) ) app . get ( ' /api/:collection/:item? ' , ( req , res ) => { req . apicacheGroup = req . params . collection res . json ( { success : true } ) } ) app . get ( ' /api/cache/performance ' , ( req , res ) => { res . json ( apicache . getPerformance ( ) ) } ) app . get ( ' /api/cache/index ' , ( req , res ) => { res . json ( apicache . getIndex ( ) ) } ) app . get ( ' /api/cache/clear/:target? ' , ( req , res ) => { res . json ( apicache . clear ( req . params . target ) ) } )

Use with middleware toggle for fine control

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 ' } ) } )

Prevent cache-control header "max-age" from automatically being set to expiration age

let cache = apicache . options ( { headers : { ' cache-control ' : ' no-cache ' , } , } ) . middleware let cache5min = cache ( ' 5 min ' )

API

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.

- 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.

- the actual middleware that will be used in your routes. is in the following format "[length][unit]", as in or . 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.

- getter/setter for middleware-specific options that will override global ones. apicache.getPerformance() - returns current cache performance (cache hit rate)

- returns current cache performance (cache hit rate) apicache.getIndex() - returns current cache index [of keys]

- 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.

- 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)

- 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

Available Options (first value is default)

{ debug : false | true , defaultDuration : ' 1 hour ' , enabled : true | false , redisClient : client , appendKey : fn ( req , res ) , headerBlacklist : [ ] , statusCodes : { exclude : [ ] , include : [ ] , } , trackPerformance : false , headers : { } }

*Optional: Typescript Types (courtesy of @danielsogl)

$ npm install -D @types/apicache

Custom Cache Keys

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 , } )

Cache Key Groups

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 app . get ( ' /api/:collection/:id? ' , cache ( ' 1 hour ' ) , function ( req , res , next ) { req . apicacheGroup = req . params . collection res . send ( { foo : ' bar ' } ) } ) app . post ( ' /api/:collection/:id? ' , function ( req , res , next ) { 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:

app . get ( ' /api/cache/index ' , function ( req , res , next ) { res . send ( apicache . getIndex ( ) ) } ) app . get ( ' /api/cache/clear/:key? ' , function ( req , res , next ) { res . send ( 200 , apicache . clear ( req . params . key || req . query . key ) ) } )

Debugging/Console Out

Using Node environment variables (plays nicely with the hugely popular debug module)

$ export DEBUG=apicache $ export DEBUG=apicache,othermoduleThatDebugModuleWillPickUp,etc

By setting internal option

import apicache from ' apicache ' apicache . options ( { debug : true } )

Client-Side Bypass

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.

Contributors

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!

@killdash9 - restify support, performance/stats system, and too much else at this point to list

@svozza - added restify tests, test suite refactor, and fixed header issue with restify. Node v7 + Restify v5 conflict resolution, etag/if-none-match support, etcetc, etc. Triple thanks!!!

@andredigenova - Added header blacklist as options, correction to caching checks

@peteboere - Node v7 headers update

@rutgernation - JSONP support

@enricsangra - added x-apicache-force-fetch header

@tskillian - custom appendKey path support

@agolden - Content-Encoding preservation (for gzip, etc)

@davidyang - express 4+ compatibility

@nmors - redis support

@maytis, @ashwinnaidu - redis expiration

@ubergesundheit - Corrected buffer accumulation using res.write with Buffers

@danielsogl - Keeping dev deps up to date, Typescript Types

@vectart - Added middleware local options support

@davebaol - Added string support to defaultDuration option (previously just numeric ms)

@Rauttis - Added ioredis support

@fernandolguevara - Added opt-out for performance tracking, great emergency fix, thank you!!

@Amhri, @Webcascade, @conmarap, @cjfurelid, @scambier, @lukechilds, @Red-Lv, @gesposito, @viebel, @RowanMeara, @GoingFast, @luin, @keithws, @daveross, @apascal, @guybrush

Changelog