Chrome Dev Summit 2020 is back & going virtual on December 9-10. Learn more

Get Started

Workbox is a set of libraries to help you write and manage service workers and caching with the CacheStorage API. Service workers and the Cache Storage API, when used together, let you control how assets (HTML, CSS, JS, images, etc…) used on your site are requested from the network or cache, even allowing you to return cached content when offline! With Workbox, you can quickly set up and manage both, and more, with production-ready code.

Installation

Starting with the v5 release, Workbox can be used inside of a service worker source file through JavaScript modules by using npm to install the Workbox modules you need and importing what you plan to use.

Unfortunately, JavaScript modules don’t work inside service workers, so you’ll need a bundler that supports JavaScript modules to compile your service worker to a single file. Popular choices include webpack, Rollup, and Parcel. Please consult the documentation for your bundler of choice for setup and configuration.

Creating a service worker

Before you can use Workbox, you need to create a service worker and register it from a web page. Start by creating a file called service-worker.js at the root of your site and add a console message to it to ensure it loads.

console.log('Hello from service-worker.js');

Next, in your web page, register your new service worker:

<script>
// Check that service workers are supported
if ('serviceWorker' in navigator) {
  // Use the window load event to keep the page load performant
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js');
  });
}
</script>

This tells the browser that this is the service worker to use for the site. If you refresh your page, open up Chrome DevTools, and navigate to the Console tab, you’ll see the log from your service worker.

Console message from sw.js in DevTools

Next, switch to the Application tab, you should see your service worker registered.

Application Tab displaying a registered service worker.

Now that you have a registered service worker, we can bring in Workbox.

Using Workbox

Workbox is distributed as a number of npm modules. When you want to use one, first install it from npm then import the portions of the modules you need for your service worker. One of Workbox’s primary features is its routing and caching strategy modules, so it’s a good place to start.

Routing and Caching Strategies

Workbox allows you to manage caching for your web app's HTTP requests using different caching strategies. The first step is to determine whether the request being worked on matches your criteria, and if so, applying a caching strategy to it. Matching happens via a callback function that returns a truthy value. Caching strategies can either be one of Workbox’s pre-defined strategies, or you can create your own. A basic service worker utilizing routing and caching could look something like this:

import { registerRoute } from 'workbox-routing';
import {
  NetworkFirst,
  StaleWhileRevalidate,
  CacheFirst,
} from 'workbox-strategies';

// Used for filtering matches based on status code, header, or both
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
// Used to limit entries in cache, remove entries after a certain period of time
import { ExpirationPlugin } from 'workbox-expiration';

// Cache page navigations (html) with a Network First strategy
registerRoute(
  // Check to see if the request is a navigation to a new page
  ({ request }) => request.mode === 'navigate',
  // Use a Network First caching strategy
  new NetworkFirst({
    // Put all cached files in a cache named 'pages'
    cacheName: 'pages',
    plugins: [
      // Ensure that only requests that result in a 200 status are cached
      new CacheableResponsePlugin({
        statuses: [200],
      }),
    ],
  }),
);

// Cache CSS, JS, and Web Worker requests with a Stale While Revalidate strategy
registerRoute(
  // Check to see if the request's destination is style for stylesheets, script for JavaScript, or worker for web worker
  ({ request }) =>
    request.destination === 'style' ||
    request.destination === 'script' ||
    request.destination === 'worker',
  // Use a Stale While Revalidate caching strategy
  new StaleWhileRevalidate({
    // Put all cached files in a cache named 'assets'
    cacheName: 'assets',
    plugins: [
      // Ensure that only requests that result in a 200 status are cached
      new CacheableResponsePlugin({
        statuses: [200],
      }),
    ],
  }),
);

// Cache images with a Cache First strategy
registerRoute(
  // Check to see if the request's destination is style for an image
  ({ request }) => request.destination === 'image',
  // Use a Cache First caching strategy
  new CacheFirst({
    // Put all cached files in a cache named 'images'
    cacheName: 'images',
    plugins: [
      // Ensure that only requests that result in a 200 status are cached
      new CacheableResponsePlugin({
        statuses: [200],
      }),
      // Don't cache more than 50 items, and expire them after 30 days
      new ExpirationPlugin({
        maxEntries: 50,
        maxAgeSeconds: 60 * 60 * 24 * 30, // 30 Days
      }),
    ],
  }),
);

This service worker caches navigation requests (for new HTML pages) with a Network First strategy storing cached pages in a cache named pages, but only if it comes back with a 200 status code. It also caches stylesheets, javascript, and web workers with a Stale While Revalidate strategy storing cached assets in a cache named assets, again, only if they come back with a 200 status code. Finally, it caches images with a Cache First strategy storing cached images in a cache named images, only if they come back with a 200 status code, expiring cached items after 30 days and only allowing 50 entries at once.

Precaching

In addition to caching as requests are made, sometimes called runtime caching, Workbox also supports precaching, the ability to cache resources when the service worker is installed. There are a number of items that are great candidates for precaching: your web app's start URL, your offline fallback page, and key JavaScript and CSS files. By precaching files, you’ll guarantee that they’re available in the cache when the service worker takes control of the page.

You can use precaching inside your new service worker by using a bundler plugin (webpack or rollup) that supports precache manifest injection:

import { precacheAndRoute } from 'workbox-precaching';

// Use with precache injection
precacheAndRoute(self.__WB_MANIFEST);

This service worker will precache files when it installs, replacing self.__WB_MANIFEST with a list of entries injected into the service worker at build time.

Offline Fallback

A common pattern for making websites and apps feel more robust when working offline is to provide a fallback page instead of displaying the browser’s default error page. With Workbox routing and precaching, you can set up this pattern in just a few lines of code:

import { precacheAndRoute, matchPrecache } from 'workbox-precaching';
import { setCatchHandler } from 'workbox-routing';

// Ensure your build step is configured to include /offline.html as part of your precache manifest.
precacheAndRoute(self.__WB_MANIFEST);

// Catch routing errors, like if the user is offline
setCatchHandler(async ({ event }) => {
  // Return the precached offline page if a document is being requested
  if (event.request.destination === 'document') {
    return matchPrecache('/offline.html');
  }

  return Response.error();
});

This service worker precaches an offline page and, if a user is offline, returns the contents of the precached offline page instead of producing a browser error.

Do more with Workbox

There’s lots more you can do with Workbox! Read the guides for a deeper dive into different aspects of Workbox. Check out all of the available Workbox modules to see even more things Workbox can do, like managing Google Analytics when offline, retrying form submissions that failed when offline, or broadcast updates when a cache is updated. With Workbox, you can harness the power of service workers to improve performance and give your site a great experience, independent of the network.

Feedback

Was this page helpful?
Yes
What was the best thing about this page?
It helped me complete my goal(s)
Thank you for the feedback. If you have specific ideas on how to improve this page, please create an issue.
It had the information I needed
Thank you for the feedback. If you have specific ideas on how to improve this page, please create an issue.
It had accurate information
Thank you for the feedback. If you have specific ideas on how to improve this page, please create an issue.
It was easy to read
Thank you for the feedback. If you have specific ideas on how to improve this page, please create an issue.
Something else
Thank you for the feedback. If you have specific ideas on how to improve this page, please create an issue.
No
What was the worst thing about this page?
It didn't help me complete my goal(s)
Thank you for the feedback. If you have specific ideas on how to improve this page, please create an issue.
It was missing information I needed
Thank you for the feedback. If you have specific ideas on how to improve this page, please create an issue.
It had inaccurate information
Thank you for the feedback. If you have specific ideas on how to improve this page, please create an issue.
It was hard to read
Thank you for the feedback. If you have specific ideas on how to improve this page, please create an issue.
Something else
Thank you for the feedback. If you have specific ideas on how to improve this page, please create an issue.