Missed the action at this year's Chrome Dev Summit? Catch up with our playlist on YouTube. Watch now.

Get Started With Workbox For Webpack

In this tutorial, you use Workbox to make a simple web app work offline.

If you'd like a conceptual overview of Workbox before starting this tutorial, see the Overview.

Step 1: Set up your project

The project that you're going to add Workbox to is hosted on Glitch. First, you need to set up Glitch so that you can edit your own copy of the project.

  1. Open the demo.

    The starting point demo, hosted on Glitch
    Figure 1. The starting point demo, hosted on Glitch

  2. Click workbox-webpack at the top-left of the page. The Project info and options dropdown appears.

  3. Click Remix This. Your browser redirects to an editable copy of the project.

Try out the initial app

The client-side JavaScript in the app fetches the top 10 Hacker News (HN) articles, and then populates the HTML with the content.

  1. Click Show. The live app appears in a new tab.

    The live app
    Figure 2. The live app

  2. In the tab that's running the live app, press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux) to open DevTools.

  3. Focus DevTools and press Command+Shift+P (Mac) or Control+Shift+P (Windows, Linux) to open the Command Menu.
  4. Type Offline, select Go offline, then press Enter. Google Chrome now has no connection to the Internet in this tab.

    The 'Go Offline' command
    Figure 3. The Go Offline command

  5. Reload the page. Google Chrome says that you're offline. In other words, the app doesn't work at all when offline.

    The initial app doesn't work at all when offline
    Figure 4. The initial app doesn't work at all when offline

  6. Open the Command Menu again, type Online, and select Go online to restore your internet connection in this tab.

  7. Reload the page.
  8. Leave the tab running the live app open.

Step 2: Install Workbox

Next, you're going to add Workbox to the project to enable an offline experience.

  1. Re-focus the tab that shows you the source code of the project.
  2. Click package.json to open that file.
  3. Click Add package.
  4. Type workbox-webpack-plugin within the Add Package text box, then click on the matching package to add it to the project.

    Adding the workbox-webpack-plugin package
    Figure 5. Adding the workbox-webpack-plugin package

Every time you make a change to your code, Glitch automatically re-builds and re-deploys your app. The tab running the live app automatically refreshes, too.

Step 3: Add Workbox to your Webpack build process

Workbox is installed, but you're not using it in your webpack build process, yet.

  1. Click webpack.config.js to open that file.
  2. Import the Workbox plugin. The bold code is the code that you need to add to your project.

    const path = require('path'),
        htmlPlugin = require('html-webpack-plugin'),
        cleanPlugin = require('clean-webpack-plugin'),
        dist = 'dist',
        workboxPlugin = require('workbox-webpack-plugin');
    

  3. Call the Workbox plugin as the last step in plugins.

    plugins: [
      new cleanPlugin([dist]),
      new htmlPlugin({
        filename: 'index.html',
        title: 'Get Started With Workbox For Webpack'
      }),
      new workboxPlugin({
        globDirectory: dist,
        globPatterns: ['**/*.{html,js}'],
        swDest: path.join(dist, 'sw.js'),
        clientsClaim: true,
        skipWaiting: true,
      })
    ]

Optional: How the config works

webpack.config.js determines how the app is built.

  • cleanPlugin deletes dist, which is the path to the output directory.
  • htmlPlugin re-generates the HTML output and places it back in dist.
  • workboxPlugin inspects the contents of dist and generates service worker code for caching the output. Since Workbox revisions each file based on its contents, Workbox should always be the last plugin you call.

The object that you pass to workboxPlugin configures how Workbox runs.

  • globDirectory is where Workbox watches for changes. globPatterns is relative to this directory.

  • globPatterns is a glob of what files to precache. In plain English, the wildcard pattern **/*.{html,js} translates to "cache every HTML and JS file in globDirectory, or any of its sub-directories".

  • swDest is where Workbox outputs the service worker that it generates.
  • clientsClaim instructs the latest service worker to take control of all clients as soon as it's activated. See clients.claim.
  • skipWaiting instructs the latest service worker to activate as soon as it enters the waiting phase. See Skip the waiting phase.

Step 4: Register and inspect the generated service worker

Workbox has generated a service worker, but there's no reference to it from your app, yet.

  1. Click src/app.js to open that file.
  2. Register your service worker at the bottom of init().

    function init() {
      let manifest = document.createElement('link');
      manifest.rel = 'manifest';
      manifest.href = '/manifest.json';
      document.head.appendChild(manifest);
      let title = document.createElement('h1');
      title.textContent = 'Top 10 Hacker News Stories';
      document.body.appendChild(title);
      let list = document.createElement('ol');
      document.body.appendChild(list);
      fetchTop10().then(stories => renderTop10(stories));
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
          navigator.serviceWorker.register('/sw.js').then(registration => {
            console.log('SW registered: ', registration);
          }).catch(registrationError => {
            console.log('SW registration failed: ', registrationError);
          });
        });
      }
    }

  3. Re-focus the tab that's running the live version of your app. In the Console of DevTools you see a message indicating that the service worker was registered.

  4. Click the Application tab of DevTools.
  5. Click the Service Workers tab.

    The Service Workers pane
    Figure 6. The Service Workers pane

  6. Click sw.js, next to Source. DevTools displays the service worker code that Workbox generated. It should look close to this:

    The generated service worker code
    Figure 7. The generated service worker code

Try out the offline-capable app

Your app now sort-of works offline. Try it now:

  1. In the live version of your app, use DevTools to go offline again. Focus DevTools and press Command+Shift+P (Mac) or Control+Shift+P (Windows, Linux) to open the Command Menu. Type Offline, select Go offline, then press Enter.
  2. Reload the page. The title of the page appears, but the list of the top 10 stories doesn't.
  3. Click the Network tab in DevTools. The request for topstories.json is red, meaning that it failed. This is why the list isn't appearing. The app tries to make a request for https://hacker-news.firebaseio.com/v0/topstories.json, but the request fails since you're offline and you haven't instructed Workbox to cache this resource, yet.

    The incomplete offline experience
    Figure 8. The incomplete offline experience

  4. Use the Command Menu in DevTools to go back online.

Optional: How the service worker code works

The service worker code in sw.js is generated based on the configuration that you provide in webpack.config.js.

  • importScripts('workbox-sw.prod.v2.1.0.js') imports Workbox's service worker library. You can inspect this file from the Sources panel of DevTools.

    The code for Workbox's service worker library
    Figure 9. The code for Workbox's service worker library

  • The fileManifest array lists all of the resources that Workbox is precaching. This list is determined by the globDirectory and globPatterns properties that you define in webpack.config.js, as mentioned in the last section.

  • Each resource has a revision property. This is how Workbox determines when to update a resource. Each time you build your app, Workbox generates a hash based on the contents of the resource. If the contents change, then the revision hash changes.
  • When the service worker runs, it writes the url and revision of each resource to IndexedDB (IDB) if it doesn't exist. If the resource does exist, the service worker checks that the revision in its code matches the revision in IDB. If the hashes don't match, then the resource has changed, and therefore the service worker needs to download the updated resource and update the hash in IDB.

In sum, Workbox only re-downloads resources when they change, and ensures that your app always caches the most up-to-date version of each resource.

Step 5: Add runtime caching

Runtime caching lets you store content that's not under your control when your app requests it at runtime. For example, by runtime caching the Hacker News content which this app relies on, you'll be able to provide an improved offline experience for your users. When users visit the app while offline, they'll be able to see the content from the last time that they had an internet connection.

  1. Re-focus the tab that shows you the source code of your project.
  2. Open webpack.config.js again.
  3. Add a runtimeCaching property to your Workbox configuration. urlPattern is a regular expression pattern telling Workbox which URLs to store locally. (When your app makes a network request at runtime, Workbox caches any request that matches the regular expression in handler, regardless of its origin. This means that you can cache content from external sites as well, as this example demonstrates.) handler defines the caching strategy that Workbox uses for any matching URL. See The Offline Cookbook for more on caching strategies.

    new workboxPlugin({
      globDirectory: dist,
      globPatterns: ['*/.{html,js}'],
      swDest: path.join(dist, 'sw.js'),
      clientsClaim: true,
      skipWaiting: true,
      runtimeCaching: [
        {
          urlPattern: new RegExp('https://hacker-news.firebaseio.com'),
          handler: 'staleWhileRevalidate'
        }
      ]
    })

Try out the complete offline experience

The app now provides a complete offline experience. Try it now:

  1. Reload the live version of your app.
  2. Use the DevTools Command Menu to go back offline.
  3. Reload the app. The app now displays the content from the last time that you were online.

    The complete offline experience
    Figure 10. The complete offline experience

  4. Use the DevTools Command Menu to go back online.

Step 6: Create your own service worker

Up until now, you've been letting Workbox generate your entire service worker. If you've got a big project, or you want to customize how you cache certain resources, or do custom logic in your service worker, such as add support for push notifications, which you're going to add in this section, then you need to create a custom service worker that calls Workbox instead. Think of the service worker code you write as a template. You write your custom logic with placeholder keywords that instruct Workbox where to inject its code.

  1. Re-focus the tab containing your project source code.
  2. Open package.json.
  3. Click Add Package, type workbox-sw, then click on the matching package to install that library.
  4. Write down the version number of workbox-sw that gets installed. You'll need it later.
  5. Add the following line of code to the init() function in app.js.

    function init() {
      let manifest = document.createElement('link');
      manifest.rel = 'manifest';
      manifest.href = '/manifest.json';
      document.head.appendChild(manifest);
      let title = document.createElement('h1');
      title.textContent = 'Top 10 Hacker News Stories';
      document.body.appendChild(title);
      let list = document.createElement('ol');
      document.body.appendChild(list);
      fetchTop10().then(stories => renderTop10(stories));
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
          navigator.serviceWorker.register('/sw.js').then(registration => {
            console.log('SW registered: ', registration);
            registration.pushManager.subscribe({userVisibleOnly: true});
          }).catch(registrationError => {
            console.log('SW registration failed: ', registrationError);
          });
        });
      }
    }

  6. Click New File, enter src/sw.js, then press Enter.

  7. Insert the following code into src/sw.js.

    // TODO: Replace Xs.
    importScripts('/node_modules/workbox-sw/build/importScripts/workbox-sw.prod.vX.X.X.js');

    // Note: Ignore the error that Glitch raises about WorkboxSW being undefined. const workbox = new WorkboxSW({ skipWaiting: true, clientsClaim: true });

    workbox.router.registerRoute( new RegExp('^https://hacker-news.firebaseio.com'), workbox.strategies.staleWhileRevalidate() );

    self.addEventListener('push', (event) => { const title = 'Get Started With Workbox For Webpack'; const options = { body: event.data.text() }; event.waitUntil(self.registration.showNotification(title, options)); });

    workbox.precache([]);

  8. Replace each X in importScripts('.../workbox-sw.prod.vX.X.X.js') with the version number of workbox-sw in package.json that you noted earlier.

  9. Open webpack.config.json.
  10. Remove the runtimeCaching, clientsClaim, and skipWaiting properties from your Workbox plugin configuration. These are now handled in your service worker code.
  11. Add the swSrc property to your Workbox plugin configuration in webpack.config.json to instruct Workbox to inject its code into a custom service worker.

    new workboxPlugin({
      globDirectory: dist,
      globPatterns: ['*/.{html,js}'],
      swSrc: './src/sw.js',
      swDest: path.join(dist, 'sw.js')
    })

Try out push notifications

The app is now all set to handle push notifications. Try it now:

  1. Re-focus the tab running the live version of your app.
  2. Click Allow when Chrome asks you if you want to grant the app permission to send push notifications. If you don't see the prompt, make sure you're online and then reload the page.
  3. Go to back to the Service Workers tab in DevTools.
  4. Enter some text into the Push text box, then click Push. Your operating system displays a push notification from the app.

    Simulating a push notification from DevTools
    Figure 11. Simulating a push notification from DevTools

Optional: How service worker injection works

At the bottom of your custom service worker, you call workbox.precache([]). This is a placeholder. At build-time, the Workbox plugin replaces the empty array with the list of resources to precache. Your Workbox plugin configuration in webpack.config.json still determines what resources get precached.

Next steps