Skip to content

Commit 3faa63d

Browse files
committed
return stale data if offline
1 parent 9abecdf commit 3faa63d

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

modules/fetch/cached.js

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,8 +146,24 @@ export async function cachedFetch(request: Request): Promise<Response> {
146146

147147
debug && console.log(`fetch(${request.url}): stale; validating`)
148148

149-
// Send request to the origin server. The server may respond with status 304
150-
let newResponse = await fetch(request)
149+
let newResponse = null
150+
try {
151+
// Send request to the origin server. The server may respond with status 304
152+
newResponse = await fetch(request)
153+
} catch (error) {
154+
// "A fetch() promise only rejects when a network error is encountered [...] not on HTTP errors such as 404"
155+
// - https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
156+
157+
// We know there's data in the cache, or we wouldn't have hit this spot.
158+
// We've made the decision to return "stale" data if we're offline, so if
159+
// we have a network error, we just do an early return with the cached
160+
// data.
161+
162+
debug && console.log(`fetch(${request.url}): offline; returning stale data`)
163+
oldResponse.headers = new Headers(oldPolicy.responseHeaders())
164+
return oldResponse
165+
}
166+
151167
let newCachePolicyResponse = responseForCachePolicy(newResponse)
152168

153169
// Create updated policy and combined response from the old and new data

0 commit comments

Comments
 (0)