Service worker caching and HTTP caching
The pros and cons of using consistent or different expiry logic across the service worker cache and HTTP cache layers.
While service workers and PWAs are becoming standards of modern web applications, resource caching has become more complex than ever. This article covers the big picture of browser caching, including:
- The use cases of and differences between service worker caching and HTTP caching.
- The pros and cons of different service worker caching expiry strategies compared to regular HTTP caching strategies.
Overview of caching flow #
At a high-level, a browser follows the caching order below when it requests a resource:
- Service worker cache: The service worker checks if the resource is in its cache and decides whether to return the resource itself based on its programmed caching strategies. Note that this does not happen automatically. You need to create a fetch event handler in your service worker and intercept network requests so that the requests are served from the service worker's cache rather than the network.
- HTTP cache (also known as the browser cache): If the resource is found in the HTTP Cache and has not yet expired, the browser automatically uses the resource from the HTTP cache.
- Server-side: If nothing is found in the service worker cache or the HTTP cache, the browser goes to the network to request the resource. If the resource isn't cached in a CDN, the request must go all the way back to the origin server.

Caching layers #
Service worker caching #
A service worker intercepts network-type HTTP requests and uses a caching strategy to determine what resources should be returned to the browser. The service worker cache and the HTTP cache serve the same general purpose, but the service worker cache offers more caching capabilities, such as fine-grained control over exactly what is cached and how caching is done.
Controlling the service worker cache #
A service worker intercepts HTTP requests with event listeners (usually the fetch
event). This code snippet demonstrates the logic of a Cache-First caching strategy.

It's highly recommended to use Workbox to avoid reinventing the wheel. For example, you can register resource URL paths with a single line of regex code.
import {registerRoute} from 'workbox-routing';
registerRoute(new RegExp('styles/.*\\.css'), callbackHandler);
Service worker caching strategies and use cases #
The next table outlines common service worker caching strategies and when each strategy is useful.