next.jsprogressive-web-appsservice-workeroffline-cachingnext-pwa

Cache offline an entire tree (or arbitrary routes) on user interaction


I have offline caching with a NextJS PWA working fairly well by following this post.

Now what I need to do is precache a set of routes (in this case all the descendents) without the visitor needing to visit every one individually (in some cases 100s of routes and media files).

I have been able to define precache pages at build time, and cache pages that are visited, but not been able to find or understand how to interactively set an offline cache. Can someone please point me in the right direction?


Solution

  • I've implemented this using a custom worker (worker/index) that accepts messages sent to the worker from the front end.

    Front end sends an action name (CACHE_ADD or CACHE_REMOVE) and a path:

      const wb = new Workbox('/sw.js')
      wb.register()
    
      return await wb.messageSW({ action, args })
    

    Worker:

    self.addEventListener('message', (event: ExtendableMessageEvent) => {
      // fetch and cache path or remove cache path
      // all done manually to match next-pwa's caching patterns
    }
    

    I also had to add a fetch handler in the service worker specifically for images using Next's <Image /> as even though the images were precached and seemed to have good cache-control they were unreliable when offline. The fetch handler just checked the cache and returned what it found.

    I've added code samples here. https://github.com/shadowwalker/next-pwa/issues/460