Course contentsShow
← Web Development
Lesson 2408 of 2,98243. Service Workers Deep DiveFree lesson

Built-In Caching Strategies

Understanding Workbox's CacheFirst, NetworkFirst, StaleWhileRevalidate, NetworkOnly, and CacheOnly strategies.

Built-In Caching Strategies

You'll learn how Workbox packages common caching patterns into ready-to-use strategies that you can apply with a single import.

The Five Core Strategies

Instead of manually coding cache logic in service workers, Workbox provides five battle-tested caching strategies you've already learned conceptually—now formalized as reusable classes:

CacheFirst checks the cache before making network requests. Perfect for static assets like images, fonts, and stylesheets that rarely change. Think of it as checking your pantry before going to the store.

NetworkFirst attempts the network, falling back to cache only if offline. Ideal for API responses and dynamic content where freshness matters most. Like checking today's weather forecast first, using yesterday's only if you have no signal.

StaleWhileRevalidate serves cached content immediately while fetching a fresh copy in the background for next time. Best for balancing speed with freshness—imagine displaying last week's news instantly while quietly loading today's edition.

NetworkOnly always hits the network, never uses cache. Useful for requests that must be fresh or shouldn't work offline (like analytics).

CacheOnly serves exclusively from cache, never touching the network. Useful for precached assets you know are already stored.

Using Them in Workbox

Each strategy is a class you import and pass to registerRoute:

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

registerRoute(
  ({request}) => request.destination === 'image',
  new CacheFirst()
);

registerRoute(
  ({url}) => url.pathname.startsWith('/api/'),
  new StaleWhileRevalidate()
);

Key Takeaway: Workbox's built-in strategies eliminate boilerplate by packaging the five fundamental caching patterns (CacheFirst, NetworkFirst, StaleWhileRevalidate, NetworkOnly, CacheOnly) into declarative, configurable classes you can immediately apply to different route patterns.