I am using workbox service worker to cache images and API responses, by creating custom caches for each. While I can see that the routes match, but I cannot see the response being stored in the cache, and the service worker is then requesting each of the resources from network due to cache miss.
I have used workbox-webpack-plugin for the service worker and writing the custom routing and caching strategies in other file, which is then passed to the plugin configuration.
On the same note, my css and js files are stored and served fine.
I have tried using different caching strategies, and a workaround without webpack plugin, but none of them seem to work
//Cache JS files
workbox.routing.registerRoute(
new RegExp('.*\.js'),
workbox.strategies.cacheFirst()
);
//Cache API response
workbox.routing.registerRoute(
new RegExp('\/api\/(xyz|abc|def)'),
workbox.strategies.staleWhileRevalidate({
cacheName: 'apiCache',
plugins : [
new workbox.expiration.Plugin({
maxEntries: 100,
maxAgeSeconds: 30 * 60 // 30 Minutes
})
]
})
);
//cache images
workbox.routing.registerRoute(
new RegExp('(png|gif|jpg|jpeg|svg)'),
workbox.strategies.cacheFirst({
cacheName: 'images',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
})
]
})
);
This is the webpack config :
new workboxPlugin.InjectManifest({
swSrc: 'customWorkbox.js',
swDest: 'sw.js'
})
Per the workbox docs the regex for an external api needs to match from the start:
Instead of matching against any part of the URL, the regular expression must match from the beginning of the URL in order to trigger a route when there's a cross-origin request.