Cloudflare Workers Causing Redirect Chain & Loops

Viewed 16

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.

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:

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

async function handleRequest(request) {
  const country = request.cf.country
  let cookies = request.headers.get('Cookie') || ""
  const url = new URL(request.url)
  let response = await fetch(request);
  response = new Response(response.body, response);

  if ((country != 'US' && country !='CA')) {
response.headers.set('Set-Cookie', "pricing-mode=on;max-age=604800;Path=/");
return response;
}

else if ((url.search.includes("gclid")) || (url.search.includes("bing")) || (url.search.includes("fbclid")) && !(cookies.includes("pricing-mode=on"))) {
response.headers.set('Set-Cookie', "pricing-mode=on;max-age=604800;Path=/");
return response;
}

  else if ((cookies.includes("pricing-mode=on"))) {
    const response = await fetch(request)
    const type = response.headers.get("Content-Type") || "";
    if (!type.startsWith("text/html")) {
     return response;
   }
    var html = await response.text()
    
    // Inject scripts
    const customMenu = '<style type="text/css">#menu-item-64460{display:block!important}</style></body>'
  html = html.replace( /<\/body>/ , customMenu)

    // return modified response
       return new Response(html, response)
}
 else {
     return fetch(request)
  }
}
0 Answers
Related