Chrome Dev Summit is back! Visit to secure your spot in workshops, office hours and learning lounges!

Generate a Complete Service Worker with Workbox CLI

This page explains how to use the Workbox Command Line Interface (a.k.a. the Workbox CLI) to generate a complete service worker with support for precaching files and setup runtime caching.

Install the CLI

To start, install the CLI from npm.

npm install workbox-cli --global

You should be able to run the command workbox --help after it's installed.

workbox --help

    workbox-cli is the command line interface for Workbox.

    $ workbox  [options]


Run the Wizard

The next step is to run the wizard. This will setup the CLI to work for your project. The wizard will ask a set of questions about your project's file structure which'll be used to determine the files that should be precached.

Start the wizard like so:

workbox wizard

Generate a Service Worker

Now that the wizard has run and created a configuration file, we can generate a service worker like so:

workbox generateSW workbox-config.js

This will generate a service worker with precaching setup to cache your site's files for offline use.

In your web page, you can register this service worker by adding:

// Check that service workers are supported
if ('serviceWorker' in navigator) {
  // Use the window load event to keep the page load performant
  window.addEventListener('load', () => {

Adding Runtime Caching

There may be files that you don't want to precache but will be used by your web app that you'd like to cache at runtime. Images are a great example.

Instead of precaching all images for your site, which will take up a lot of space in the cache, you can cache them as they are used and limit the number of images cached.

To do this, edit the config file used to generate the service worker, by default this is workbox-config.js.

Runtime caching can be achieved by adding the runtimeCaching options. This expects an array of objects that describe the runtime caching rules you want.

In the example below, we'll demonstrate how to cache images and limit that cache to a maximum of 10 images.

module.exports = {
  globDirectory: 'build/',
  globPatterns: [
  swDest: 'build/sw.js',

  // Define runtime caching rules.
  runtimeCaching: [{
    // Match any request that ends with .png, .jpg, .jpeg or .svg.
    urlPattern: /\.(?:png|jpg|jpeg|svg)$/,

    // Apply a cache-first strategy.
    handler: 'CacheFirst',

    options: {
      // Use a custom cache name.
      cacheName: 'images',

      // Only cache 10 images.
      expiration: {
        maxEntries: 10,

The full set of available options can be found on the Workbox CLI module page.