Cache.match always returns undefined

I have the following worker:

  async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    if (req.method !== "GET") {
      return new Response("Method Not Allowed", {status: 405});
    }

    const cacheKey = req.url
    const cache = caches.default;

    let response = await cache.match(cacheKey);

    if (response) {
      console.log(`HIT: ${req.url}`);

      return response;
    }

    console.log(`MISS: ${req.url}`);

    const objectKey = new URL(cacheKey).pathname.slice(1);
    const object = await env.IMAGES.get(objectKey);

    if (object === null) {
      response = new Response("Not Found", {status: 404});
    } else {
      const headers = new Headers();
      object.writeHttpMetadata(headers);
      headers.set("etag", object.httpEtag);
      headers.append("Cache-Control", "public, max-age=31536000, s-maxage=31536000, immutable");
      response = new Response(object.body, {headers})
    }

    ctx.waitUntil(cache.put(cacheKey, response.clone()));

    return response;
  }

However, it does not work (ironic). I opened my image and refreshed the page a couple of times. None of requests was a hit.

Where are you testing this? If it’s on workers.dev for example, cache operations do not work.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.