Is it possible to use Workflare workers to cache an API


I’m trying to follow this tutorial to cache the response of an API (living on a google cloud function):

The thing is that no matter the header I include, or the key I use for the cache, the request is not being cached. The line in

  let response = await cache.match(cacheKey)

always means a missed cache hit.

This is the code i’m trying to use:

async function handleRequest(event) {
  const request = event.request
  const cacheUrl = new URL(request.url)

  // Construct the cache key from the cache URL
  // const cacheKey = new Request(cacheUrl.toString(), request)
  // const cacheKey = cacheUrl.toString();;
  const cacheKey = request.url;
  const cache = caches.default

  // Check whether the value is already available in the cache
  // if not, you will need to fetch it from origin, and store it in the cache
  // for future access
  let response = await cache.match(cacheKey)

  if (!response) {
    console.log("Cache fail")
    // If not in cache, get it from origin

    var newurl = "";
    // If not in cache, get it from origin
    response = await fetch(newurl);

    response = new Response(response.body, 
        "headers": {
          "Cache-Control": "public, max-age=604800, immutable",

    // Store the fetched response as cacheKey
    // Use waitUntil so you can return the response without blocking on
    // writing to cache
    event.waitUntil(cache.put(cacheKey, response.clone()))
  } else {
    console.log("Cache hit")
  return response

addEventListener("fetch", event => {
  try {
    const request = event.request
    return event.respondWith(handleRequest(event))
  } catch (e) {
    return event.respondWith(new Response("Error thrown " + e.message))