What's the difference between cache.put(url, response) and cache.put(request, response)

Assuming you have the following code:

const cache = caches.default;
const url = “https://www.example.com”;
const request = new Request(url, init);

cache.put(url, response);

How is that different from:

cache.put(request, response);

There must be a difference or else there wouldn’t be the option to put a request instead of a URL. I have been using the latter because it allows me to put a cacheTTL as part of the init object, but is that the only thing that makes any difference? Does that even make any difference?

The first parameter in cache.put is also called cacheKey.

This cacheKey can be a URL string or a Request object: cache.put(cacheKey, new Response('hello')).

If cacheKey is a URL string you are telling Cloudflare to cache everything based on the URL you provided as the cacheKey. I recommend this option if you only need 1 version of your content to be put in cache.

With cache.put(request, response) you´ll have more control of what you are putting in cache. Variations in the properties of the Request (cf, headers, body, method, redirect) could create several versions of your content, even if the URLs are the same.

cache.put throws an error if:

  • the request passed is a method other than GET
  • the response passed is a status of 206 Partial Content Open external link
  • the response passed contains the header Vary: * (required by the Cache API specification)