g000m
g000m

Reputation: 135

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?

Upvotes: 1

Views: 80

Answers (1)

Justin Collins
Justin Collins

Reputation: 350

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
}

Upvotes: 1

Related Questions