Course contentsShow
← Web Development
Lesson 2317 of 2,98242. Progressive Web AppsFree lesson

The Cache Storage API

Open, store, and retrieve resources from named caches available to service workers.

The Cache Storage API

What you'll learn: How to programmatically open, store, and retrieve resources from named caches that service workers use for offline functionality.

What Is the Cache Storage API?

The Cache Storage API provides a set of methods for managing multiple named caches in the browser. Think of it like a filing cabinet where each drawer (cache) has a name, and inside each drawer you store pairs of requests and responses. Unlike localStorage or sessionStorage, the Cache Storage API is designed specifically for storing full HTTP request/response pairs, making it perfect for offline-capable PWAs.

Core Operations

The API centers around three main actions:

Opening a cache using caches.open(cacheName) returns a Promise that resolves to a Cache object. If the cache doesn't exist, it creates one:

caches.open('my-cache-v1').then(cache => {
  // Now you can work with this cache
});

Storing resources with cache.put(request, response) or the convenience method cache.add(url):

cache.add('/index.html'); // Fetches and stores automatically
cache.put(request, response); // Stores a specific response

Retrieving resources using cache.match(request):

cache.match('/index.html').then(response => {
  if (response) {
    // Cache hit! Use the cached response
  }
});

You can also use caches.match() (without opening a cache first) to search across all caches, and caches.delete(cacheName) to remove an entire cache.

The Connection to Service Workers

While the Cache Storage API is accessible from both service workers and regular scripts, it truly shines inside service workers where you intercept fetch events and serve cached responses, enabling offline functionality.

Key Takeaway: The Cache Storage API lets you create named caches and store request/response pairs programmatically, forming the foundation for offline-capable Progressive Web Apps.