# Stale-while-revalidate — Progressive Web Apps

Source: https://www.geekswithgeeks.com/en/pwa/pwa-stale-while-revalidate

> Implement stale-while-revalidate: serve cached content immediately, update asynchronously.

## Best of both worlds

**Stale-while-revalidate** serves cached content immediately for speed, then updates the cache in the background. Users get instant feedback while fresh data is fetched asynchronously.

## Stale-while-revalidate implementation

Serve from cache immediately, fetch fresh data in background, update cache.

```javascript
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.open('v1').then(cache => 
      cache.match(event.request).then(response => {
        const fetchPromise = fetch(event.request).then(networkResponse => {
          cache.put(event.request, networkResponse.clone());
          return networkResponse;
        });
        return response || fetchPromise;
      })
    )
  );
});
```

Output:

```
Cached content served instantly; fresh version fetched and cached in background.
```

Quick check

**Quiz:** What is the main benefit of stale-while-revalidate?

- [x] Instant response to users while fresh data updates in background
- [ ] Always serving the newest content
- [ ] Reducing server load completely

*Answer:* Instant response to users while fresh data updates in background. This strategy balances speed (instant cache) with freshness (background fetch).
