Subscribe to receive notifications of new posts:

Cache API for Cloudflare Workers is now in Beta!

2018-09-14

2 min read

In October of last year we announced the launch of Cloudflare Workers. Workers allows you to run JavaScript from 150+ of Cloudflare’s data centers. This means that from the moment a request hits the Cloudflare network, you have full control over its destiny. One of the benefits of using Workers in combination with Cloudflare’s cache is that Workers allow you to have programmatic, and thus very granular control over the Cloudflare cache.

You can choose what to cache, how long to cache it for, the source it should be cached from, and you can even modify the cached result after it is retrieved from the cache.

We have seen many of our existing customers use Workers to enhance their usage of the Cloudflare cache, and we have seen many new customers join Cloudflare to take advantage of these unique benefits.

(Re-)Introducing the Cache API

You can always have more control, so today we are announcing support for the Cache API! As some of you may know, Cloudflare Workers are built against the existing Service Worker APIs. One of the reasons we originally chose to model Cloudflare Workers after Service Workers was due to the existing familiarity and audience of Service Workers, as well as documentation.

We’ve received overwhelming feedback and evidence from customers that there are many uses for supporting an implementation modeled after the Service Workers Cache API. Today we are opening up a beta to offer our customers the ability to explicitly read and write items in our cache from within their Workers. The capability to do this will allow them to implement virtually any cache semantics they might need.

So what can you do with the Cache API?

Cache Worker output

Workers allow you to fully customize and manipulate a response before it is sent back to the user. Whether you are modifying the response from your origin, or assembling a response based on calls to multiple APIs, you can use the Cache API to cache the output and serve it directly on future similar requests.

async function handleRequest(event) {
    let cache = caches.default
    let response = await cache.match(event.request)
        
    if (!response) {
      response = doSuperComputationallyHeavyThing()
      event.waitUntil(cache.put(event.request, response.clone()))
    }
          
    return  response
}

Cache POST requests

Cloudflare ordinarily doesn’t cache POST requests because they can change state on a customer’s origin. However, some APIs and frameworks like GraphQL make every call a POST request, including those that do not change state. For these APIs it’s important to enable caching to speed things up.

async function handleRequest(event) {
    let cache = caches.default
    let response = await cache.match(event.request)
    
    if (!response){
      response = await fetch(event.request)
      if (response.ok) {
        event.waitUntil(cache.put(event.request, response.clone()))
      }
    }
          
    return response
}

Set Cache-Tag headers from a Worker (Enterprise only)

One of the ways to purge assets within the Cloudflare cache is using Cache-Tags. Cache-Tags allow you to group assets by category, version, etc and purge them all at once using a single API call. Cache-Tags were traditionally set using an origin Cache-Tag header. Some backends, however, don’t allow you control over the response headers that are sent, which makes it challenging to set Cache-Tags at the origin. With the Cache API, you can set Cache-Tags directly from a Worker, without having to modify any code at your origin.

addEventListener('fetch', event => {
 event.respondWith(handleRequest(event))
})

/**
* Fetch a request and add a tag
* @param {Request} request
*/
async function handleRequest(event) {
  let request = event.request
  let cache = caches.default
  let response = await cache.match(request)
  if (!response) {
    response = await fetch(request)
    if (response.ok) {
      response = new Response(response.body, response)
      response.headers.append('Cache-Tag', 'apple')
      event.waitUntil(cache.put(request, response.clone()))
    }
  }
  return response
}

These are just simple examples to get started, and we’ll be publishing many more in the coming weeks. We’re excited to see what everyone builds with the Cache API!

How to get access

We are super excited for you to start playing with the Cache API. You can find documentation here, and feel free to start using the APIs.

We want to hear about all the cool ways you are using this. We also want to hear if you are having trouble or running into any issues.

Please feel free to contact us at [email protected]

Cloudflare's connectivity cloud protects entire corporate networks, helps customers build Internet-scale applications efficiently, accelerates any website or Internet application, wards off DDoS attacks, keeps hackers at bay, and can help you on your journey to Zero Trust.

Visit 1.1.1.1 from any device to get started with our free app that makes your Internet faster and safer.

To learn more about our mission to help build a better Internet, start here. If you're looking for a new career direction, check out our open positions.
Cloudflare WorkersServerlessBetaCacheAPIJavaScriptDevelopersDeveloper Platform

Follow on X

Rita Kozlov|@ritakozlov_
Cloudflare|@cloudflare

Related posts