Cache.match miss but fetch hit?

#1

I’m trying to write a CF worker that caches files from a B2 bucket so that users don’t have to send all traffic to B2 every time to get the same file over and over. ( I know the BW is free already, but seems excessive and worse for the user ).

In my worker I’m running:

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

and response is always empty. After catching this, and running fetch to get the request I’m then seeing a header with cf-cache-status: HIT which means that the request is in the cache - so why is it missing the original cache ?

Here is the code I’m using -

The headers I’m adding, n-cache is always ‘miss’, but after the second request cf-cache-status: HIT is returned. Is there something I’m doing wrong? I’m using a Pro plan, so I don’t have Enterprise features, but from the documentation it implied that cache.put was still available on responses.

#2

Here are the headers returned from a second request -

curl -I https://mydomain.com/files/1/1/64MB-1-0-1.rar
HTTP/2 200 
date: Wed, 24 Apr 2019 12:41:39 GMT
content-type: application/octet-stream
content-length: 67108864
set-cookie: __cfduid=df8da78995940fdb8a662d330eb9bb9eb1556109699; expires=Thu, 23-Apr-20 12:41:39 GMT; path=/; domain=.mydomain.com; HttpOnly; Secure
cf-cache-status: HIT
cache-control: public, max-age=31556926
cf-ray: 4cc82716af0ace15-LHR
accept-ranges: bytes
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
expires: Thu, 23 Apr 2020 18:30:25 GMT
n-cache: miss
n-sha1: dfc79790bd946d6f8293b17f932af7639d9acbdf
server: cloudflare
#3

I came across that when browser Origin Header mismatches worker route URL.
My solution(adding request.url) for GET method:

let response    = await cache.match(request.url)
...
event.waitUntil(cache.put(request.url, response.clone()))
#4

Thank you, that worked. I tried that earlier on in the debugging process but must have bamboozled myself. It seems to also work if you create a new request object with the URL which I’m guessing strips the headers ?

    rewritten_request = new Request("https://mydomain.com" + rewrite_url, {
        method: request.method
    })