Skip to content

Cache-Only & Network-Only — Extreme Caching Strategies

DodaTech Updated 2026-06-28 6 min read

In this tutorial, you will learn about Cache. We cover key concepts, practical examples, and best practices to help you master this topic.

Cache-only serves exclusively from cache while network-only never caches — two extreme strategies for edge cases where either the cache or the network must be the sole source of truth.

What You'll Learn

By the end of this tutorial, you will understand when to use cache-only and network-only strategies, how to implement both, and why most applications rarely need these extremes in isolation.

Why It Matters

While hybrid strategies like stale-while-revalidate cover most use cases, some situations demand strict control. Cache-only ensures content works offline regardless of network state. Network-only prevents Caching sensitive data or ensures the freshest possible response. Understanding both extremes gives you a complete toolkit.

Real-World Use

A hiking trail PWA uses cache-only for trail maps that are pre-cached during install. These maps never change and must always work offline, even at the bottom of a canyon with no signal. The same PWA uses network-only for user authentication to prevent cached tokens from granting access to old sessions.

Cache-Only Strategy

Cache-Only Flow
    Request comes in
         ↓
    ╔═══════════════════════╗
    ║  Check cache          ║
    ╚═══════════════════════╝
         ↓
    ┌─────────┐             ┌──────────────┐
    │  Found  │             │  Not Found   │
    └────┬────┘             └──────┬───────┘
         ↓                         ↓
    Return cached            Return error
    response                  (no fallback)

Think of cache-only like a vending machine that only dispenses items already stocked. If the item is in the machine, you get it instantly. If it is not stocked, you get nothing — there is no option to order from the warehouse.

Cache-Only Implementation

self.addEventListener('fetch', event => {
    if (event.request.method !== 'GET') return;

    const url = new URL(event.request.url);

    // Apply cache-only to pre-cached reference content
    if (url.pathname.startsWith('/reference/')) {
        event.respondWith(
            caches.match(event.request).then(cachedResponse => {
                if (cachedResponse) {
                    console.log('Cache-only: HIT', event.request.url);
                    return cachedResponse;
                }
                console.log('Cache-only: MISS', event.request.url);
                return new Response('Content not available offline', {
                    status: 503,
                    statusText: 'Service Unavailable',
                    headers: { 'Content-Type': 'text/plain' }
                });
            })
        );
    }
});

Output:

Cache-only: HIT https://example.com/reference/offline-map.png
Cache-only: MISS https://example.com/reference/unavailable-doc.pdf

Network-Only Strategy

Network-Only Flow
    Request comes in
         ↓
    ╔═══════════════════════╗
    ║  Fetch from network   ║
    ╚═══════════════════════╝
         ↓
    ┌──────────────┐        ┌──────────────┐
    │  Network     │        │  Network     │
    │  success     │        │  fails       │
    └──────┬───────┘        └──────┬───────┘
           ↓                       ↓
    Return fresh              Return error
    response                  (no cache fallback)

Think of network-only like a food delivery service that only brings food from restaurants. There is no fridge (cache) to store leftovers. If the restaurant is closed (network down), you get nothing.

Network-Only Implementation

self.addEventListener('fetch', event => {
    if (event.request.method !== 'GET') return;

    const url = new URL(event.request.url);

    // Apply network-only to authentication endpoints
    if (url.pathname.startsWith('/auth/')) {
        event.respondWith(
            fetch(event.request).then(response => {
                console.log('Network-only:', event.request.url);
                return response;
            }).catch(error => {
                console.log('Network-only failed:', error.message);
                return new Response('Authentication requires network', {
                    status: 503,
                    statusText: 'Service Unavailable',
                    headers: { 'Content-Type': 'text/plain' }
                });
            })
        );
    }
});

Output:

Network-only: https://example.com/auth/verify-token
Network-only failed: TypeError: Failed to fetch

When to Use Cache-Only

Use cache-only when:

  • Content never changes: Reference documents, EULAs, license files
  • Offline is mandatory: Trail maps, emergency guides, boarding passes
  • Pre-cached during install: App shell for kiosk applications
  • Versioned build files: Old versions should never update

When to Use Network-Only

Use network-only when:

  • Sensitive data: Authentication tokens, passwords, credit card info
  • Real-time requirements: Stock trades, live auctions, game moves
  • Idempotent operations: Each request must reflect current server state
  • Third-party iframes: Analytics, ads, embedded widgets

Combining Strategies with Request Matching

Use URL and request patterns to apply different strategies to different resources:

self.addEventListener('fetch', event => {
    const { request } = event;
    const url = new URL(request.url);

    // Skip non-GET
    if (request.method !== 'GET') return;

    // Strategy selection based on URL patterns
    if (url.pathname.startsWith('/static/') ||
        url.pathname.match(/\.(css|js|woff2?)$/)) {
        // Static assets: cache-first
        event.respondWith(cacheFirst(request));

    } else if (url.pathname.startsWith('/reference/')) {
        // Reference content: cache-only
        event.respondWith(cacheOnly(request));

    } else if (url.pathname.startsWith('/auth/') ||
               url.hostname === 'analytics.example.com') {
        // Sensitive: network-only
        event.respondWith(networkOnly(request));

    } else if (url.pathname.startsWith('/api/')) {
        // API: stale-while-revalidate
        event.respondWith(staleWhileRevalidate(request));

    } else {
        // Everything else: network-first
        event.respondWith(networkFirst(request));
    }
});

function cacheOnly(request) {
    return caches.match(request).then(response => {
        if (response) return response;
        return new Response('Not cached', { status: 503 });
    });
}

function networkOnly(request) {
    return fetch(request).catch(() => {
        return new Response('Network required', { status: 503 });
    });
}

function cacheFirst(request) { /* ... */ }
function networkFirst(request) { /* ... */ }
function staleWhileRevalidate(request) { /* ... */ }

Cache-Only with Pre-Caching Verification

For cache-only to work, resources must be pre-cached during install. Verify everything is cached:

self.addEventListener('install', event => {
    const REQUIRED_RESOURCES = [
        '/reference/map-v1.png',
        '/reference/guide-v1.pdf',
        '/reference/eula-v2.html'
    ];

    event.waitUntil(
        caches.open('reference-v1').then(cache => {
            return cache.addAll(REQUIRED_RESOURCES);
        }).then(() => {
            // Verify all resources were cached
            return caches.open('reference-v1').then(cache => {
                return Promise.all(REQUIRED_RESOURCES.map(url => {
                    return cache.match(url).then(response => {
                        if (!response) {
                            throw new Error(`Failed to cache: ${url}`);
                        }
                        console.log('Verified cached:', url);
                    });
                }));
            });
        }).then(() => self.skipWaiting())
    );
});

Output:

Verified cached: https://example.com/reference/map-v1.png
Verified cached: https://example.com/reference/guide-v1.pdf
Verified cached: https://example.com/reference/eula-v2.html

Common Mistakes

  1. Using cache-only without pre-caching. Cache-only with an empty cache serves nothing. Always pre-cache resources during install when using cache-only.
  2. Using network-only for critical content. If the network fails, the user gets nothing. Use network-only only for non-critical or non-essential requests.
  3. Caching sensitive data accidentally. Network-only prevents caching, but verify that no other part of your service worker caches these responses.
  4. Applying cache-only broadly. Cache-only on a large set of resources bloats storage. Be selective about what truly needs offline exclusivity.
  5. Forgetting to handle errors gracefully. Both strategies should return meaningful error responses (status 503, offline page) rather than throwing unhandled exceptions.

Practice Questions

  1. When would you use cache-only instead of cache-first?
  2. Why should authentication endpoints use network-only?
  3. What happens if cache-only encounters a request it has not cached?
  4. How do you verify that cache-only resources are pre-cached correctly?
  5. Can you combine both strategies in the same service worker?

Challenge: Create a service worker that uses cache-only for reference documents (pre-cached during install), network-only for authentication endpoints, and cache-first for everything else. Test each scenario with DevTools.

FAQ

Does cache-only ever make network requests?

No. Cache-only never calls fetch(). If the resource is not in cache, it returns an error. This is the strictest offline guarantee.

Is network-only the default browser behavior?

Almost. Without a service worker, the browser always goes to the network. Network-only in a service worker explicitly prevents any caching logic from applying.

Can I cache POST responses with network-only?

POST responses should never be cached. The network-only strategy correctly skips caching entirely, which is safe for all HTTP methods.

What happens to cache-only resources when the cache is cleared?

They are gone. The next request fails with 503. You need to re-register the service worker and re-install to pre-cache them again.

Does network-only work offline?

No. Network-only requires a network connection. If offline, it returns a 503 error. Use network-first or stale-while-revalidate for offline resilience.

Mini Project

Create a service worker that implements three zones: cache-only for 5 pre-cached reference documents, network-only for 3 authentication-style endpoints, and stale-while-revalidate for all other same-origin resources. Pre-cache the documents during install and verify each strategy works using DevTools network and cache storage panels.

What's Next

You have mastered the five caching strategies. Now apply them with offline fallback patterns to create graceful degradation when the network is unavailable.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro