Skip to content

Commit

Permalink
fix: Do not serve cached opaque responses if possible (#8950)
Browse files Browse the repository at this point in the history
We don't know whether an opaque response was a success, so if we're
serving the response from cache indefinetely, we might serve broken
versions till the next update. To avoid this, only serve opaque
responses if the network request threw an exception.
Right now, dynamic images are not cached by the service worker this
way, but the browser should do caching, too. Right now it's not possible
to request these with CORS.
  • Loading branch information
Dschoordsch authored Oct 12, 2023
1 parent 540a6de commit bcc4664
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions packages/client/serviceWorker/sw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,21 @@ const onFetch = async (event: FetchEvent) => {
if (isCacheable) {
const cachedRes = await caches.match(request.url)
// all our assets are hashed, so if the hash matches, it's valid
if (cachedRes) return cachedRes
const networkRes = await fetch(request)
const cache = await caches.open(DYNAMIC_CACHE)
// cloning here because I'm not sure if we must clone before reading the body
cache.put(request.url, networkRes.clone()).catch(console.error)
return networkRes
// let's skip opaque responses because we don't know whether they're valid
if (cachedRes && cachedRes.type !== 'opaque') {
return cachedRes
}
try {
const networkRes = await fetch(request)
const cache = await caches.open(DYNAMIC_CACHE)
// cloning here because I'm not sure if we must clone before reading the body
cache.put(request.url, networkRes.clone()).catch(console.error)
return networkRes
} catch (e) {
// if we have an opaque cached response, it's better than nothing
if (cachedRes) return cachedRes
throw e
}
// } else if (request.destination === 'document') {
// // dynamic because index.html isn't hashed (and the server returns an html with keys)
// const dynamicCache = await caches.open(DYNAMIC_CACHE)
Expand Down

0 comments on commit bcc4664

Please sign in to comment.