Skip to main content

StaleWhileRevalidate

First added

Workbox

About

An implementation of the stale-while-revalidate request strategy.

Resources are requested from both the cache and the network in parallel. The strategy will respond with the cached version if available, otherwise wait for the network response. The cache is updated with the network response with each successful request.

By default, this strategy will cache responses with a 200 status code as well as opaque responses. Opaque responses are are cross-origin requests where the response doesn’t support CORS.

If the network request fails, and there is no cache match, this will throw a SerwistError exception.

Parameters

  • cacheName — Cache name to store and retrieve requests. Defaults to Serwist’s default cache names.
  • pluginsPlugins to use in conjunction with this caching strategy.
  • fetchOptions — Options passed to non-navigation fetch() calls made by this strategy.
  • matchOptions — The CacheQueryOptions passed to any cache.match() or cache.put() call made by this strategy.

Usage

import { StaleWhileRevalidate, Serwist } from "serwist";

const serwist = new Serwist({
  runtimeCaching: [
    {
      matcher: ({ url }) => url.pathname.startsWith("/images/avatars/"),
      handler: new StaleWhileRevalidate(),
    },
  ],
});

More resources

Here is a list of resources you can read to learn more about StaleWhileRevalidate: