Custom Expiration Logic (Client-Side)

Implements logic within the service worker itself to manage expiration based on timestamps or other criteria. Developers store timestamps or other expiration information alongside cached resources within the service worker.

Service Worker Implementation:

JavaScript
async function cacheAndStoreTimestamp(request, response) {
    const cache = await caches.open('my-cache');
    const timestamp = Date.now();
    const responseWithTimestamp =
        new Response(response.body,
            {
                ...response.headers,
                'X-Cache-Timestamp': timestamp
            });
    await cache.put(request, responseWithTimestamp);
}

async function handleFetch(event) {
    const cachedResponse =
        await caches.match(event.request);
    if (cachedResponse) {
        const cacheTimestamp =
            cachedResponse.headers.get('X-Cache-Timestamp');
        const isFresh =
        
            // Implement logic based on 
            // timestamp and expiration duration
            isFresh(cacheTimestamp, expirationTimeInMs);
        if (isFresh) {
            return cachedResponse;
        }
    }
    return fetch(event.request);
}

function isFresh(cacheTimestamp, expirationTimeInMs) {
    const now = Date.now();
    const cachedTime = parseInt(cacheTimestamp);
    return now - cachedTime < expirationTimeInMs;
}

Explanation of isFresh function:

  • It takes the cached timestamp and expiration time in milliseconds as arguments.
  • It calculates the difference between the current time (now) and the cached time (cachedTime).
  • A cached response is considered fresh if the difference is less than the expiration time.

Output:

The service worker's behavior depends on the implemented logic.
If a fresh cached response exists (based on cache-control headers or custom logic), it's returned.
If the cached response is expired or not found, the service worker fetches new resources from the network.

How to Set an Expiration Date for Items in a Service Worker Cache using JavaScript?

Service workers empower web applications to cache resources for offline access and improved performance. However, outdated cached data can negatively impact user experience.

This article explores two effective strategies for setting expiration dates for cached items within a service worker using JavaScript, ensuring your application delivers fresh content.

Table of Content

  • Cache-Control Headers
  • Custom Expiration Logic

Similar Reads

Cache-Control Headers (Server-Side Configuration)

Relies on server configuration to instruct the service worker on caching duration. The server sends cache-control headers with responses, specifying how long to cache resources. Common directives include:...

Custom Expiration Logic (Client-Side)

Implements logic within the service worker itself to manage expiration based on timestamps or other criteria. Developers store timestamps or other expiration information alongside cached resources within the service worker....

Choosing the Right Approach

Cache-Control Headers: Ideal for simpler setups with server-side configuration, but may lack flexibility for dynamic content.Custom Expiration Logic: Offers greater control and adaptability for complex scenarios or when granular expiration management is needed....

Conclusion

By adding metadata to your cached items and checking expiration times during fetch events, you can effectively manage the lifecycle of your cache. This ensures your web application remains performant and up-to-date with the latest content. Implementing these techniques in your service worker will help maintain a healthy cache, enhancing user experience and reliability....

Contact Us