Recursion when fetching the same url inside worker

I have an API URL which is hosted on GCP. (CNAME (api = googlehosted))
URL - https://api.example.com

I have built a worker which caches the response of this API. If the data is not in the cache, the worker fetches the response from the origin server on GCP.

response = fetch(request)
when I fetch the response from the browser by hitting https://api.example.com I get an error because of recursion. It seems instead of calling global fetch, local fetch is being called.
My notion is that this fetch inside the worker will resolve to CNAME value but it calls itself.

I am using “wrangler”: “2.9.1” and routing to intercept requests.

See if your Worker is receiving a redirect which goes in a loop.

Not sure what you meant. It is receiving the request and looping it.

I put a simple code:

export default {
async fetch(request, env, ctx) {
let response = await fetch(request);
response = new Response(response.body, response);
return response
}
}

Still the same issue. It is looping.

It was getting redirected from the origin server. It seems when a request goes through the worker, if SSL is not enabled for the website on the Cloudflare dashboard, the worker won’t add a certificate with the request. My server was configured to redirect requests which are not secure.

Thanks for the hint, helped me work backwards.

The interesting thing to notice here is that requests behave differently when passed through workers and proxied without workers.

Is your encryption mode set to Full (strict)? Are you using Workers Routes or Custom Domains?

It was not full and that was causing recursion. Upon changing it to full, things started working. I am using routes to intercept the requests.