100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

What Is the Cache API and How Does It Differ From HTTP Caching?

Learn how the Cache API differs from HTTP caching, how Service Workers use it, and a cache-first strategy code example.

mediumQ174 of 224 in Web Development Est. time: 6 minsLast updated:
Open Code Lab

Expected Interview Answer

The Cache API is a programmable, script-controlled storage mechanism for Request/Response pairs that a Service Worker uses to explicitly decide what to store and serve offline, unlike the browser’s built-in HTTP cache, which is governed passively by response headers like Cache-Control.

Where the HTTP cache is a black box the browser manages automatically based on freshness headers, the Cache API exposes an explicit `caches.open(name)` interface returning a `Cache` object with `put()`, `match()`, `add()`, and `delete()` methods, letting a Service Worker store exact Request/Response pairs under a named cache and later intercept `fetch` events to serve them regardless of what caching headers the response carried. This is what powers offline app-shell strategies: on install, the Service Worker can pre-cache core assets with `cache.addAll([...])`, and on every subsequent fetch it can implement cache-first, network-first, or stale-while-revalidate strategies by directly querying and writing to that cache. Multiple named caches can coexist (e.g., versioned per deploy), and old ones are typically cleaned up in the `activate` event to avoid unbounded storage growth. The two systems can layer together: the HTTP cache still applies to any request the Service Worker doesn’t intercept, while the Cache API gives full manual control for anything the app wants to guarantee is available offline.

  • Gives explicit, code-driven control over what is cached and for how long
  • Enables offline-capable app shells independent of server cache headers
  • Supports custom strategies like cache-first, network-first, and stale-while-revalidate
  • Works with exact Request/Response objects, preserving headers and body for later replay

AI Mentor Explanation

HTTP caching is like a kiosk automatically deciding, based on a printed expiry label, whether to keep reusing a scorecard or fetch a new one. The Cache API is like a groundskeeper who deliberately walks around before the match, manually filing away specific scorecards and equipment lists into a labeled locker, so they can hand them out instantly during play regardless of any expiry label. The groundskeeper decides exactly what goes in the locker and when to clear it out for a new season. That deliberate, code-driven filing system is what the Cache API gives a Service Worker, versus the automatic label-based system of HTTP caching.

Step-by-Step Explanation

  1. Step 1

    Open a named cache

    The Service Worker calls `caches.open("app-shell-v1")` to get a `Cache` object scoped to that name.

  2. Step 2

    Store Request/Response pairs

    On `install`, `cache.addAll([...urls])` or `cache.put(request, response)` explicitly stores specific assets.

  3. Step 3

    Intercept fetch events

    On every `fetch` event, the Service Worker calls `cache.match(request)` to decide whether to serve from cache or hit the network.

  4. Step 4

    Clean up old caches

    On `activate`, old versioned cache names are deleted so storage does not grow unbounded across deploys.

What Interviewer Expects

  • Clear contrast between programmable Cache API control and passive HTTP cache header behavior
  • Understanding of `caches.open`, `put`/`add`, `match`, and cache versioning
  • Ability to describe at least one strategy (cache-first, network-first, stale-while-revalidate)
  • Awareness that old caches must be cleaned up in the `activate` event

Common Mistakes

  • Conflating the Cache API with the browser’s automatic HTTP cache
  • Forgetting to version cache names, causing stale assets to persist across deploys
  • Not cleaning up old caches in `activate`, leading to unbounded storage growth
  • Assuming Cache API entries expire automatically like HTTP max-age — they do not, expiry is manual

Best Answer (HR Friendly)

The Cache API lets a website’s background script explicitly choose what files to save for offline use, rather than relying on the browser’s automatic caching rules. It is what makes an app shell load instantly even with no internet, because the app itself decided in advance exactly what to store and when to refresh it.

Code Example

Cache-first strategy with versioned cleanup
const CACHE_NAME = 'app-shell-v3'
const APP_SHELL = ['/', '/index.html', '/styles.css', '/app.js']

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL))
  )
})

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((names) =>
      Promise.all(
        names.filter((name) => name !== CACHE_NAME).map((name) => caches.delete(name))
      )
    )
  )
})

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((cached) => cached || fetch(event.request))
  )
})

Follow-up Questions

  • How would you implement a stale-while-revalidate strategy with the Cache API?
  • Why is manual cache versioning necessary when using the Cache API?
  • How does the Cache API interact with the HTTP cache for requests the Service Worker does not intercept?
  • What are the storage quota and eviction risks with the Cache API on mobile?

MCQ Practice

1. What primarily governs the browser’s built-in HTTP cache?

The HTTP cache is passive and driven by caching headers the server sends.

2. What method stores an explicit Request/Response pair in the Cache API?

`cache.put()` (or `cache.add`/`addAll`) explicitly stores Request/Response pairs in a named Cache.

3. Why must old cache versions be deleted in the `activate` event?

Cache API entries persist until explicitly deleted, so version cleanup avoids storage bloat.

Flash Cards

How is the Cache API different from the HTTP cache?It is explicitly script-controlled, not governed by response headers.

What opens a named cache?`caches.open(name)`, returning a `Cache` object.

What checks for a cached response during fetch?`cache.match(request)` inside a `fetch` event handler.

Why clean up old caches in `activate`?Cache API entries never auto-expire, so stale versions must be deleted manually.

1 / 4

Continue Learning