0.0.8 • Published 9 months ago

workers-swr v0.0.8

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

Workers-SWR

Utility to add stale-while-revalidate and stale-if-error (see rfc5861) handling to Cloudflare workers via the Workers Cache API.

Usage

The library is very minimalistic and requires almost no code changes, just install the library via:

npm i workers-swr

Then import and wrap your fetch handler with the provided withSWR function:

import { withSWR } from "workers-swr";

export default {
  fetch: withSWR(
    // your standard fetch handler goes here
    (request, env, ctx) => {
      return new Response("Hello World!");
    }
  ),
};

The library will check incoming requests and outgoing responses and implement the swr caching for you.

Warning Note that the workers cache API, which this library uses, is not available in *.workers.dev deployments, in order to make use of it you need to deploy your worker to a custom domain.

Note Cloudflare adds a default 4-hour max-age caching to fetch responses, this means that this library by default will make your responses be cached for 4 hours, you can easily change this by changing accordingly the Browser Cache TTL option in the Cloudflare dashboard.

Demo

Demo on how this library works (source code): https://workers-swr-demo.dariopiot.net/

To implement

Essential items yet to be implemented

Items that could potentially be implemented (nice to have but not essential)

  • [] adding a config parameter can be passed to withSWR to enable the must-understand directive

  • [] adding the possibility to use a different caching storage (e.g. using KVs instead of the cache api, allowing caching also on workers.dev subdomains) (important note: this would also need to make sure we handle all the cache control directives that now the workers api handles for us)

0.0.8

9 months ago

0.0.7

9 months ago

0.0.6

9 months ago

0.0.5

9 months ago

0.0.4

9 months ago

0.0.3

9 months ago

0.0.2

9 months ago

0.0.1

10 months ago

0.0.0

10 months ago