Course contentsShow
← Security
Lesson 1076 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

Cache API and Service Worker Storage

Security of Cache API, service worker caches, and preventing sensitive data leakage through browser caching mechanisms.

Cache API and Service Worker Storage

You'll learn how service workers and the Cache API can inadvertently leak sensitive data if not handled with security in mind.

What Are Service Workers and the Cache API?

Service workers are JavaScript files that run in the background of web applications, enabling offline functionality by intercepting network requests. The Cache API provides persistent storage that service workers use to cache responses—like HTML pages, images, or API results—so your app works even without internet.

Think of a service worker like a personal assistant who keeps copies of documents you might need later, stored in a filing cabinet (the cache). But what if sensitive documents get filed there and aren't properly secured?

The Security Risk

The Cache API stores data origin-scoped (respecting the Same-Origin Policy), but it persists across sessions and is accessible to any JavaScript running on that origin. Key risks include:

  • Sensitive data caching: API responses with user details, tokens, or private information might be cached indefinitely
  • Unauthorized access: Any script on the same origin can read cached data using caches.open()
  • No automatic expiration: Unlike HTTP cache headers, Cache API entries persist until explicitly deleted
  • Debugging exposure: Developers might cache authentication tokens or PII during development, forgetting to remove caching logic

Protection Strategies

Never cache sensitive data like authentication tokens, personal information, or payment details. Use explicit cache naming and careful request filtering:

// BAD: Caching everything including sensitive endpoints
self.addEventListener('fetch', event => {
  event.respondWith(caches.match(event.request));
});

// GOOD: Selective caching, excluding sensitive paths
self.addEventListener('fetch', event => {
  const url = new URL(event.request.url);
  if (url.pathname.startsWith('/api/user')) {
    return; // Don't cache sensitive endpoints
  }
  // Cache only public assets
});

Set appropriate Cache-Control: no-store headers server-side for sensitive endpoints, and regularly purge old caches.

Key Takeaway: Service workers provide powerful caching, but you must explicitly exclude sensitive data from Cache API storage to prevent information leakage across sessions and to unauthorized scripts on your origin.