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:

  • max-age: Maximum duration (in seconds) a resource can be cached.
  • expires: Absolute expiration date for the resource.

Syntax:

const express = require('express');
const app = express();

app.get('/my-resource', (req, res) => {
res.setHeader('Cache-Control', 'max-age=3600'); // Cache for 1 hour
res.sendFile('path/to/my-resource.js');
});

app.listen(3000, () => console.log('Server listening on port 3000'));

Service Worker Implementation:

The service worker intercepts requests and checks cached responses cache-control headers for freshness.

Example:

JavaScript
async function handleFetch(event) {
    const response = await caches.match(event.request);
    if (response) {
        const cacheHeaders =
            response.headers.get('Cache-Control');
        if (isFresh(cacheHeaders)) {
            return response;
        }
    }
    return fetch(event.request);
}
async function isFresh(cacheHeaders) {

    // Implement logic to parse cache-control 
    // headers and determine freshness
    // This is a simplified example, assuming 
    // presence of a 'max-age' directive
    const maxAge =
        parseInt(cacheHeaders.match(/max-age=(\d+)/)?.[1]);
    if (maxAge) {
        const now = Date.now();
        const responseTime =
            parseInt(response.headers.get('Date'));
            
        // Assuming responseTime is available
        const age = now - responseTime;
        return age < maxAge * 1000;
        
        // Convert maxAge seconds to milliseconds
    }
    return false;
    // Default to not fresh if max-age not found
}

Explanation of isFresh function :

  • The isFresh function now attempts to parse the cacheHeaders for the max-age directive using a regular expression.
  • It retrieves the response time from the response.headers (assuming it’s available) and calculates the age of the cached response.
  • It compares the age with the max-age converted to milliseconds and returns true if fresh, false otherwise.

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