Cache dynamic content 15min

caching

#1

Hi,

I want to do something like below:

  1. check URL if it match http://example.com/blog/post/*
  2. check cache exist by url (include query string)
  3. if cache exist, return cache content.
  4. if not exist fetch and cache it 15 min.

Does the free plan can do the above?


#2

:wave: @DDdev,

Yes s you can use a cache everything page rule for this.

-OG


#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


#4

:wave: @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


#5

It could be done most likely via the Cache API in the workers.

Try looking into it:


#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
};

#7

@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
};

#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.