Workers fetch: always getting cf-cache-status:BYPASS

I have a worker which is requesting an image from external source and this source is always returning cache-control: no-store and setting cookies.

I want cloudflare to cache the response and ignore cache-control but so far I am without success.

I have tried enabling page rules on worker path with following : Browser Cache TTL: 4 hours, Cache Level: Cache Everything, Edge Cache TTL: 4 hours but it didn’t work

I have also tried setting cf property inside the worker and rewriting the headers but that also didn’t work.

            let response = await fetch(theUrl, {
                headers: reqHeaders,
                cf: {
                    cacheTtl: 900,
                }
            });
            response = new Response(response.body, response)

            response.headers.set('Cache-Control', 'public, max-age=3600')
            return response

Any ideas ?

You cannot cache an image if it isn’t hosted on your site. If you’d like to cache the image, try uploading it to your site, CloudFlare will cache it then.

Workers have better control over the cache API, see here:

4 Likes

They currently use a worker and handle the cache, the problem is the external source. CloudFlare doesn’t cache external sources

This is workers, it can cache anything you want (within the limits).

“Store responses on a zone scoped namespace separate from Cloudflare’s traditional cache using the Cache API from a Workers script. One can control cache behavior of even assets not proxied on Cloudflare.”

1 Like

How are you checking the headers for the external source? If the workers control cache over everything as @thomas4 said, you should be able to view the headers from the network tab of Google Chrome or Firefox. If you wouldn’t mind, could you send your domain and the external source you are trying to cache?

Yes, the solution was to use the cache API via workers. Thanks, @thomas4.

Example of code I used, for anyone else that might be in the same situation.

            const cacheKey = event.request;
            const cache = caches.default;

            let response = await cache.match(cacheKey);
            if (!response) {

                const reqHeaders = new Headers(someCustomHeadersObj);

                response = await fetch(theUrl, {
                    headers: reqHeaders
                });

                response = new Response(response.body, response);

                // I needed to override headers from response for my use case
                response.headers.set('Cache-Control', 'public, max-age=3600');
                response.headers.delete('set-cookie');
                event.waitUntil(cache.put(cacheKey, response.clone()))
            }
            return response
3 Likes

You’re welcome, thanks for sharing your solution :slight_smile:

1 Like