HTTP response caching for Koa

Koa Cash

HTTP response caching for Koa. Caches the response based on any arbitrary store you'd like.

  • Handles JSON and stream bodies
  • Handles gzip compression negotiation
  • Handles 304 responses
  // some options 
app.use(function* (next) {
  // this response is already cashed if `true` is returned, 
  // so this middleware will automatically serve this response from cache 
  if (yield* this.cashed()) return
  // set the response body here, 
  // and the upstream middleware will automatically cache it 
  this.response.body = 'hello world!'

Options are:

Default max age for the cache if not set via yield* this.cashed(maxAge).

Minimum byte size to compress response bodies. Default 1kb.

A hashing function. By default, it's:

function hash(_this) {
  return this.request.url

this is the Koa context and is also passed as an argument. By default, it caches based on the URL.

Get a value from a store. Must return a "yieldable", which returns the cache's value, if any.

function get(keymaxAge) {
  return <yieldable>

Note that all the maxAge stuff must be handled by you. This module makes no opinion about it.

Set a value to a store. Must return a "yieldable".

function set(keyvaluemaxAge) {
  return <yieldable>

Note: maxAge is set by .cash={ maxAge }. If it's not set, then maxAge will be 0, which you should then ignore.

Using a library like lru-cache, though this would not quite work since it doesn't allow per-key expiration times.

var cache = require('lru-cache')({
  maxAge: 30000 // global max age 
  getfunction* (keymaxAge) {
    return cache.get(key)
  setfunction* (keyvalue) {
    cache.set(key, value)

This is how you enable a route to be cached. If you don't call yield* this.cashed(), then this route will not be cached nor will it attempt to serve the request from the cache.

maxAge is the max age passed to get().

If cached is true, then the current request has been served from cache and __you should early return__. Otherwise, continue setting this.response.body= and this will cache the response.

  • Only GET and HEAD requests are cached.
  • Only 200 responses are cached. Don't set 304 status codes on these routes - this middleware will handle it for you
  • The underlying store should be able to handle Date objects as well as Buffer objects. Otherwise, you may have to serialize/deserialize yourself.