DDdev
October 12, 2018, 2:09pm
#1
Hi,
I want to do something like below:
check URL if it match http://example.com/blog/post/*
check cache exist by url (include query string)
if cache exist, return cache content.
if not exist fetch and cache it 15 min.
Does the free plan can do the above?
@DDdev ,
Yes s you can use a cache everything page rule for this.
-OG
eva2000
October 12, 2018, 7:36pm
#3
One thing is Cache Everything with Edge TTL Cache has max cache times depending on Cloudflare plan https://support.cloudflare.com/hc/en-us/articles/200168376-What-does-edge-cache-expire-TTL-mean- and lowest on free is 2hrs and Pro 1hr and Business 30mins. So you won’t be able to set max 15 min cache time unless on Cloudflare Enterprise plan
Cloudflare offers a range of edge cache TTLs by plan type:
Free 2 hours
Pro 1 hour
Business 30 minutes
Enterprise as low as 30 seconds
@eva2000 ,
Good point! @DDdev you would need to set the TTL to 15 minutes on your origin as a page rule specified TTL of 15 minutes isn’t an option.
-OG
matteo
October 12, 2018, 10:47pm
#5
It could be done most likely via the Cache API in the workers.
Try looking into it:
2 Likes
DDdev
October 13, 2018, 12:54am
#6
Thanks guys,
I know that page rules can do that, but need Enterprise plan for 15 min cache, it’s impossible for me.
So my idea is use worker to do that, I follow the official blog post https://blog.Cloudflare.com/cache-api-for-Cloudflare-workers-is-now-in-beta/ , but not success on tools https://Cloudflareworkers.com/ .
For example, I use follow workers but not work:
self.addEventListener('fetch', event => event.respondWith(handle(event)))
async function handle(event) {
let cache = caches.default
let response = await cache.match(event.request)
if (!response) {
response = await fetch(event.request)
event.waitUntil(cache.put(event.request, response.clone()))
}
return response
};
@DDdev Try this. It will overwrite your server:
self.addEventListener('fetch', event => event.respondWith(handle(event)))
async function handle(event) {
const cache_time = 900
let cache = caches.default
let response = await cache.match(event.request)
if (!response) {
response = await fetch(event.request, {
cf: {
cacheTtl: cache_time
}
});
event.waitUntil(cache.put(event.request, response.clone()))
}
return response
};
3 Likes
DDdev
October 14, 2018, 11:38pm
#8
Thanks @adaptive , seems it’s what I looking for. but the cache API not really work on https://Cloudflareworkers.com , I need to test it on production later.
Thanks all.
1 Like