Lesson 13 / 30

Workbox: Caching Without Boilerplate

Use Google's Workbox to precache assets and apply cache-first, network-first and stale-while-revalidate routes in a few lines.

Why Workbox

Workbox is a set of libraries that wraps the Cache and Fetch APIs. It handles precaching with versioning, routing and the common caching strategies, so you write less service-worker code and make fewer cache-bug mistakes.

Routes and strategies

Precache the build output and register a strategy per request type.

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

precacheAndRoute(self.__WB_MANIFEST);

registerRoute(({ request }) => request.destination === 'image',
  new CacheFirst({ cacheName: 'images' }));
registerRoute(({ request }) => request.mode === 'navigate',
  new NetworkFirst({ cacheName: 'pages' }));
registerRoute(({ url }) => url.pathname.startsWith('/api/'),
  new StaleWhileRevalidate({ cacheName: 'api' }));

Generate the precache manifest at build time with workbox-webpack-plugin or vite-plugin-pwa instead of listing files by hand.

Quick check

Quick check: What does Workbox precaching do?

  • Caches versioned build assets during install
  • Encrypts the cache
  • Disables the service worker
  • Blocks network requests
Answer

Caches versioned build assets during install — Precaching stores assets up front and updates them when their revision changes.