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

Runtime Caching with registerRoute

Defining routes to cache resources at runtime using URL patterns and matching functions.

Runtime Caching with registerRoute

You'll learn how to define flexible caching routes in Workbox that intercept specific requests and apply caching strategies at runtime.

What Is Runtime Caching?

Unlike precaching (where you cache files during service worker installation), runtime caching happens dynamically as your users navigate your app. Workbox's registerRoute() method lets you define which requests should be cached and how they should be handled—without manually writing fetch event listeners.

Think of registerRoute() as setting up traffic rules for your service worker: "When you see a request matching this pattern, handle it with this strategy."

How registerRoute() Works

You pass two arguments to registerRoute():

  1. A matcher - Defines which requests this route handles (URL pattern, regular expression, or custom function)
  2. A handler - Specifies the caching strategy (CacheFirst, NetworkFirst, etc.)
import { registerRoute } from 'workbox-routing';
import { CacheFirst } from 'workbox-strategies';

// Cache images using Cache-First strategy
registerRoute(
  ({request}) => request.destination === 'image',
  new CacheFirst({
    cacheName: 'images-cache'
  })
);

// Match specific URL patterns
registerRoute(
  /\.(?:png|jpg|jpeg|svg|gif)$/,
  new CacheFirst({
    cacheName: 'image-assets'
  })
);

You can also use custom matching functions for complex logic:

registerRoute(
  ({url, request}) => {
    return url.pathname.startsWith('/api/') && 
           request.method === 'GET';
  },
  new NetworkFirst({
    cacheName: 'api-cache'
  })
);

This approach keeps your service worker code clean and declarative—you describe what to cache rather than how to intercept every fetch event.

Key Takeaway: registerRoute() lets you define URL-based or function-based rules that automatically apply caching strategies to matching requests, making runtime caching flexible and maintainable.