function cacheApiMiddleware
Since 0.2.0
cacheApiMiddleware(options?: CacheApiMiddlewareOptions): MiddlewareFunction

Caches responses in the Cloudflare edge cache.

On a hit the cached response is replayed and the handler chain is not invoked. On a miss the handler runs and its response is stored in the background through ICloudflareBindings.waitUntil, so the write never delays the client.

Skipped without error, each reported as X-Cache-Api: BYPASS or MISS:

  • bypass returned true;
  • no cache handle is available (not running on Cloudflare Workers);
  • the response is a live stream — teeing it would double the memory the stream exists to avoid and change its flush timing (the M42 guard cache-plugin also applies);
  • assessCacheability found a refusal, so put would have thrown.

Two platform properties are worth knowing before relying on this: caches.default is per-datacenter, so it is a latency optimisation and not a shared store; and it is scoped to the zone, so a key must be unique across every route that caches.

One testing note: a HIT is replayed with IResponse.stream, so a cached response of any size reaches the client without being buffered — which means app.inject() cannot read its body. Drive a cached route with app.fetch and a web Request, which is what a Worker invokes anyway.

Examples

Example 1

app.router.get('/catalog', listCatalog, {
  middleware: [cacheApiMiddleware({ ttlSeconds: 300 })],
});

Parameters

optional
options: CacheApiMiddlewareOptions

Cache handle, key, bypass, cacheable statuses, and TTL

Return Type

MiddlewareFunction

The middleware function

Usage

import { cacheApiMiddleware } from "cloudflare-plugin/src/index.ts";