Using the Cache API - why do the examples show this?

In the “Using the Cache API” example, our query to the cache is prepared like this:

async function handleRequest(event) {
  const request = event.request
  const cacheUrl = new URL(request.url)

  const cacheKey = new Request(cacheUrl.toString(), request)
  const cache = caches.default

  let response = await cache.match(cacheKey)

  // ...
}

This seems redundant.

Why does the example convert request.url to a new URL object, only to then convert that object back into a string while constructing a new object for cacheKey? The documentation states that the first parameter to the cache.match() method can be either a string or a Request, so why is it necessary to jump through all of those hoops? Why does this example not just use the request.url or the original request as the key?

Perhaps this example is verbose for the sake of demonstration, but I just want to be clear that I’m not missing or misunderstanding anything here.

I agree that the example is unneeded and have an open an issues to correct it.

1 Like

This is how I understand it:
If all you want is to cache by the URL than you don’t need to do all this. Just match by the URL, as you said.
However, caching by request object will consider more than just the URL. It will also use some headers, the request method, etc.
By passing a request object, you have a chance to create a request object that will represent exactly the data that you wish to be used as cache key.
You can make 2 distinct requests use the same key, for example by removing a query param or removing the origin header, or split 2 requests by a header that is not normally part of the key.
The new Request object also accepts a Cloudflare options object that can contain cacheKey property, which you can set to make any 2 requests “the same” or “different” for the cache layer.

See the Request object
See: cache keys - not specific to workers, but still explains things

1 Like

Thanks for the explanation.

You seem to be correct in the fact that some attributes of the request body are used as the cache key. I first assumed it would just use the URL of the provided request body as the key, but after some confused testing it showed that was not the case.

It is a useful feature but the documentation should be more clear in explaining this.