Workbox is a library created by Google that simplifies Service Worker development. It provides production-ready caching strategies, routing, precaching, and background sync — all with minimal boilerplate.
# Install Workbox CLI
npm install workbox-cli --global
# Or add to your project
npm install workbox-webpack-plugin --save-dev
npm install workbox-sw --save
// sw.js - Using Workbox from CDN
importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
if (workbox) {
console.log('Workbox loaded successfully');
} else {
console.log('Workbox failed to load');
}
// sw.js with workbox-build (recommended approach)
// Use workbox-webpack-plugin or workbox-build to generate this
const { precacheAndRoute } = workbox.precaching;
precacheAndRoute(self.__WB_MANIFEST);
// The manifest is auto-generated by workbox-build
// It lists all static assets to precache
// Register routes with different strategies
workbox.routing.registerRoute(
/\.(?:js|css|html)$/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: 'static-resources'
})
);
workbox.routing.registerRoute(
/\.(?:png|jpg|jpeg|svg|gif|webp)$/,
new workbox.strategies.CacheFirst({
cacheName: 'image-cache',
plugins: [
new workbox.expiration.ExpirationPlugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
}),
new workbox.cacheableResponse.CacheableResponsePlugin({
statuses: [0, 200]
})
]
})
);
workbox.routing.registerRoute(
/\/api\//,
new workbox.strategies.NetworkFirst({
cacheName: 'api-cache',
plugins: [
new workbox.expiration.ExpirationPlugin({
maxEntries: 50,
maxAgeSeconds: 5 * 60, // 5 minutes
})
]
})
);
// webpack.config.js
const { InjectManifest } = require('workbox-webpack-plugin');
module.exports = {
plugins: [
new InjectManifest({
swSrc: './src/sw.js',
swDest: 'sw.js',
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
})
]
};
// Background Sync
const bgSyncPlugin = new workbox.backgroundSync.BackgroundSyncPlugin('my-queue', {
maxRetentionTime: 24 * 60 // Retry for 24 hours
});
workbox.routing.registerRoute(
/\/api\/sync\//,
new workbox.strategies.NetworkOnly({
plugins: [bgSyncPlugin]
}),
'POST'
);
// Broadcast Update (notify page when cached content updates)
workbox.routing.registerRoute(
/\.(?:js|css)$/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: 'static-assets',
plugins: [
new workbox.broadcastUpdate.BroadcastUpdatePlugin({
channelName: 'precache-updates'
})
]
})
);