Search code examples
progressive-web-appsworkbox

Workbox StaleWhileRevalidate and offline fallback


Is it possible to return an offline fallback for StaleWhileRevalidate strategie with Workbox ?

const urlHandler = new StaleWhileRevalidate({
  cacheName: 'routes',
  plugins,
});

registerRoute(
  ({ request }) => request.mode === 'navigate',
  ({ event }) =>
    urlHandler.handle({ event }).catch(() => caches.match(FALLBACK_HTML_URL)),
);

This code work only if the request is on cache .. but for new URL not cached (but with network), it show directly the Offline fallback :/

Anyone have already test this usecase ?


Solution

  • In Workbox v6+, the cleanest way to do this would be to use a handlerDidError plugin:

    import {registerRoute} from 'workbox-routing';
    import {StaleWhileRevalidate} from 'workbox-strategies';
    
    
    registerRoute(
      ({request}) => request.mode === 'navigate',
      new StaleWhileRevalidate({
        cacheName: 'routes',
        plugins: [
          {handlerDidError: () => caches.match(FALLBACK_HTML_URL)},
          // Add any other plugins here.
        ],
      })
    );