Search code examples
javascriptservice-workerbrowser-cachecloudflarecloudflare-workers

Cloudflare workers: prevent 302 (from disk cache) for a URL with param


I have a worker I want to bypass cache when URL has a specific param this way:

      let wcApiParam = url.searchParams.get('wc-api');

      //bypass cache if wc-api param is in the URL
      if( wcApiParam != 'auth'  ){
        //force cache
        response = await fetch( newRequest, { cf: { cacheTtl: 43200 } } );
      } else {
          //bypass cache
          response = await fetch( newRequest, { cf: { cacheTtl: 0 } } );
      }

Im not sure what Im doing wrong, the response of the request is always 302 (from disk cache) this is causing errors in my site, because I need to avoid these requests from being cached. What could be wrong with my worker? or maybe something wrong in my cache settings?

below is the full response:

Request response


Solution

  • It looks like the problem is that the response has been cached in your browser's cache. The request is not actually hitting Cloudflare at all (and therefore your Worker isn't executing).

    The browser has cached the response because it has Cache-Control: max-age=14400. This tells the browser it can cache the response for 4 hours. You should either stop sending this header from your origin, or you could have your Worker script remove the header from responses that shouldn't be cached in the browser, like:

    let response = await fetch(...);
    
    // Copy the response so that headers can be modified.
    response = new Response(response);
    
    // Remove cache-control header.
    response.headers.delete("Cache-Control");