Search code examples
nuxt.jsworkbox

Workbox not Overriding Default Strategy


Having some issues overriding the default cacheFirst strategy in Nuxt Workbox.

Expected behavior: cacheFirst is replaced by staleWhileRevalidate

nuxt.config.js:

workbox: {
  runtimeCaching: [
    {
      urlPattern: '/_nuxt/.*',
      handler: 'staleWhileRevalidate',
      method: 'GET'
    }
  ]
}

Current behavior: Creates a new entry instead of overriding.

sw.js:

workbox.routing.registerRoute(new RegExp('/_nuxt/.*'),
workbox.strategies.cacheFirst({}), 'GET')

workbox.routing.registerRoute(new RegExp('/.*'), 
workbox.strategies.networkFirst({}), 'GET')

workbox.routing.registerRoute(new RegExp('/_nuxt/.*'), 
workbox.strategies.staleWhileRevalidate({}), 'GET')

Not sure what I am missing. Thank you for the help. Cheers!


Solution

  • I seemed to have sort of resolved this by adding to nuxt.config.js:

    workbox: {
      cachingExtensions: '@/plugins/wb-ext.js'
    }
    

    Then my wb-ext.js contains:

    workbox.routing.registerRoute(new RegExp('/_nuxt/.*'), 
    workbox.strategies.staleWhileRevalidate({
      plugins: [
        new workbox.broadcastUpdate.Plugin('new-update-channel')
      ]
    }), 'GET')
    

    This adds the wb-ext code above the auto generated cacheFirst strategy created by Nuxt Workbox in the sw.js file.

    Now during Dev, I get a message stating Workbox is using StaleWhileRevalidate in the Dev Console, and the broadcast update plugin works as expected.

    Feel free to comment if you have a cleaner way of achieving this without having conflicting strategies in the sw.js file.

    Thank you!