Cache workers behavior

Hello :slight_smile:

Whats the difference between

response = await fetch(request, {
cf: {
cacheEverything: true,
cacheTtl: 3600
}
});

Than

let cache = caches.default
let response = await cache.match(request)

if (response == null)
{
response = await fetch(request, {
cf: {
cacheEverything: true,
cacheTtl: 3600
}
});
}

Thanks!

the first is cache on the fetch.
the second is cache on the worker, but the code is incomplete.

Sorry I still don’t understand what actually is the difference, and why the second on is not complete, can you elaborate ?

Hi @dan19,

caches.default controls the same HTTP cache as fetch() does, so there’s no functional difference between the two snippets. The second snippet will be a little slower if the response is not already cached because it checks the cache twice (once with cache.match(), once with fetch()), but the end result of both snippets should be the same: the response will end up cached with a TTL of 3600.

If all you need to do is cache a response from the origin as-is, it’s best to rely on fetch(request, { cf: { cacheTtl: 3600 } })'s caching behavior. Note that cacheTtl implies cacheEverything.

You’d typically only need to use the Cache API if you must modify the response in some way in the worker, e.g. to set a custom Cache-Control or Cache-Tag header.

Harris

4 Likes

Thanks