DEV Community

Cover image for PWA Caching Strategies
Peeyush Man Singh
Peeyush Man Singh

Posted on

PWA Caching Strategies

Caching strategies determine how a PWA behaves when the app makes a network request and how it deals with network failures. Workbox is a commonly used library for creating PWA; workbox-strategies provides the following caching strategies.

Stale-While-Revalidate

The service worker will serve the cached assets first, and update the cache with the latest version afterwards. On cache-hit, it responds to the request as quickly as possible. On cache-miss, the request falls back to network request. The response from network request is then used to update the cache. This strategy is useful in situation where receiving a response has higher priority over having most up-to-date results.

Cache First

The service worker will serve the cached assets and will only query the network if the cache is not available. On cache-hit, it will not update the cache in background; the network will not be used at all. On cache-miss, the request will be sent over the network and the response will be cached. The next request will then be served from the cache. This strategy is useful for requests for static assets, which do not change frequently.

If no caching strategy is defined, Workbox will use Cache First as default.

Network First

The service worker will by default try to fetch the response over the network. If the network request fails, it will serve the response from the cache. On successful response over the network, it will cache the response for future use. This strategy can be useful in requests that update frequently.

Network Only

The service worker will always query the network for response. This can be useful if you require to query the network strictly.

Cache only

The service worker will always query the cache for response. You need to make sure that you pre-cache resources before requesting. This strategy is less used in practice.

Example Usage

On your service-worker.ts, add a custom strategy for a fetch event.
Note: You could also define custom events for different fetch requests by filtering depending on URL origin or path.

import { StaleWhileRevalidate } from "workbox-strategies";

...

//! Stale-While-Revalidate for all fetch events
self.addEventListener("fetch", (event) => {
    const { request } = event;

    event.respondWith(new StaleWhileRevalidate().handle({ event, request }));
});
Enter fullscreen mode Exit fullscreen mode

Workbox also allows you to define custom strategies. All of these strategies also allow you to configure name of cache, cache expiration and an array of additional workbox plugins.

Happy Hacking!

Top comments (2)

Collapse
 
aybee5 profile image
Ibrahim Abdullahi Aliyu

You should change your code snippet to js for mire readability

Collapse
 
pssingh21 profile image
Peeyush Man Singh

Thanks for the feedback!