title: Cloudflare Workers Causing Redirect Chain & Loops
body: <p>Forgive me for a more generalized question, but I have spent a few weeks developing these cloudflare worker scripts that I believe can be of huge use to the community - however, I am experiencing significant redirect chains and loops on my SEM Rush Scan (Some 7+ of the same exact url) - and it seems to be relevant to my Cloudflare Workers.</p>
  <p>This is my current worker code, I will be editing this to exclaim what is included within so other users can copy the perfected code in the future:</p>
  <pre><code>addEventListener('fetch', event =&gt; {
      event.passThroughOnException()
      event.respondWith(handleRequest(event.request))
  })
  
  async function handleRequest(request) {
    const country = request.cf.country
    let cookies = request.headers.get('Cookie') || &quot;&quot;
    const url = new URL(request.url)
    let response = await fetch(request);
    response = new Response(response.body, response);
  
    if ((country != 'US' &amp;&amp; country !='CA')) {
  response.headers.set('Set-Cookie', &quot;pricing-mode=on;max-age=604800;Path=/&quot;);
  return response;
  }
  
  else if ((url.search.includes(&quot;gclid&quot;)) || (url.search.includes(&quot;bing&quot;)) || (url.search.includes(&quot;fbclid&quot;)) &amp;&amp; !(cookies.includes(&quot;pricing-mode=on&quot;))) {
  response.headers.set('Set-Cookie', &quot;pricing-mode=on;max-age=604800;Path=/&quot;);
  return response;
  }
  
    else if ((cookies.includes(&quot;pricing-mode=on&quot;))) {
      const response = await fetch(request)
      const type = response.headers.get(&quot;Content-Type&quot;) || &quot;&quot;;
      if (!type.startsWith(&quot;text/html&quot;)) {
       return response;
     }
      var html = await response.text()
      
      // Inject scripts
      const customMenu = '&lt;style type=&quot;text/css&quot;&gt;#menu-item-64460{display:block!important}&lt;/style&gt;&lt;/body&gt;'
    html = html.replace( /&lt;\/body&gt;/ , customMenu)
  
      // return modified response
         return new Response(html, response)
  }
   else {
       return fetch(request)
    }
  }
  </code></pre>