Search code examples
cloudflarecloudflare-workers

validate response before caching with Cloudflare page rule


I’ve created a Cloudflare page rule to cache a static page as follows:

domain.com/
Cache Level: cache everything
Edge Cache TTL: 2 hours

There’s generally no problem, but several times the server has returned an error, or there’s been a connection timeout, and Cloudflare has cached this result. How can I test for a valid response before caching the page?


Solution

  • You should be able to check the status of the response before you do any caching.

    response.ok returns true if the status code is within 200 to 299. You can interrogate the status directly with response.status

    const response = await fetch(event.request);
    if(response.ok) {
        // ... do caching logic
    }