CF Workers & PWA/Workbox interaction?

Because I lack javascript coding knowledge, I used Google Workbox which allowed me to build out a basic pre-cache/offload mode basic service worker for PWA conversion of my sites.

Workbox starts via importing workbox-sw.js

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.6.1/workbox-sw.js');

if (workbox) {
  console.log(`Yay! Workbox is loaded 🎉`);
} else {
  console.log(`Boo! Workbox didn't load 😬`);
}

Google Workbox makes it easier i.e. to cache first configure a service worker I just use

workbox.routing.registerRoute(
  /\.(?:png|gif|jpg|jpeg|svg)$/,
  workbox.strategies.cacheFirst({
    cacheName: 'images',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 60,
        maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
      }),
    ],
  })
);

to cache Google fonts via Workbox

// Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.
workbox.routing.registerRoute(
  /^https:\/\/fonts\.googleapis\.com/,
  workbox.strategies.staleWhileRevalidate({
    cacheName: 'google-fonts-stylesheets',
  })
);

// Cache the underlying font files with a cache-first strategy for 1 year.
workbox.routing.registerRoute(
  /^https:\/\/fonts\.gstatic\.com/,
  workbox.strategies.cacheFirst({
    cacheName: 'google-fonts-webfonts',
    plugins: [
      new workbox.cacheableResponse.Plugin({
        statuses: [0, 200],
      }),
      new workbox.expiration.Plugin({
        maxAgeSeconds: 60 * 60 * 24 * 365,
        maxEntries: 30,
      }),
    ],
  })
);

But when I asked Cloudflare support whether Workbox is compatible with CF Workers, they said it wouldn’t be. Not sure if that has changed but was curious to know what this means for other CF users who have existing service workers setup on origin side and how that is meant to interact with Cloudflare Workers ?

Does that mean origin side service worker code needs to be moved/converted into non-Workbox to a Cloudflare Worker ?

I want to keep having PWA and precaching functionality on my sites but also want to try out Cloudflare Workers. At this stage due to my limited javascript/service worker knowledge, it looks like I can only try either PWA on origin via Workbox or CF Workers and not both ?

Anyone have examples or links to articles I can read for this ?

2 Likes