← Back to Tutorials Chapter 9

Workbox

What is Workbox?

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.

Setup

# 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

Using Workbox via CDN

// 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');
}

Precaching with Workbox

// 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

Runtime Caching Strategies

// 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
      })
    ]
  })
);

Workbox Webpack Plugin

// 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,
    })
  ]
};

Advanced Features

// 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'
      })
    ]
  })
);
Exercise: Set up Workbox in a project using the Webpack plugin. Configure precaching for all static assets, a CacheFirst strategy for images with a 30-day expiration, and a NetworkFirst strategy for API calls. Build and verify the generated Service Worker.