Workers: "observe" a request

[sorry for bad english]

I just started checking out workers and it’s amazing. It makes me sad that I discovered it so late. Also, I am a beginner generally speaking and I stumbled upon workers a few days back and I don’t know how to explain what I want to achieve.

I want to ask is there any way to only “observe” a request?

Say, I have a 3rd party service at www.MyDomainWithCloudFlare.com/someApi

What I understood so far is:
if I assign a worker to the route - www.MyDomainWithCloudFlare.com/someApi, whenenver this api is called, the worker will be invoked and I shall write the code to take care of request and response modification.

query1:
mostly, I just want to observe what is the request, and what is the response, and take action only in some cases. E.g. whenever www.MyDomainWithCloudFlare.com/someApi is called make changes if it is from one particular country, or if the response is empty. for rest of the cases - usual behavior shall follow(behavior as if worker isn’t deployed). Do I have to handle all the request that comes to the worker or only these that I want to modify. Is there any way to say do what would have been done if the worker weren’t present?

query2:
if I have to handle all requests, my worker gets invoked when www.MyDomainWithCloudFlare.com/someApi is fetched by the browser. And inside the worker I’ll make a fetch to “www.MyDomainWithCloudFlare.com/someApi”, will this become a loop?

Yes; all requests for the path you choose will be handled by the worker. The most you can do for conditional triggering is to only apply a worker to a more specific path like example.com/admin/* to have it trigger there but not for the rest of your website.

The default worker script it gives you on https://cloudflareworkers.com is the default behavior that just passes through requests like you’re asking:

async function handleRequest(request) {
  const response = await fetch(request)
  return response
}

In order to prevent such a loop, all fetch calls from your worker to the same zone/domain will bypass all worker scripts and go directly to your origin server.

1 Like

Thank you so much. That clarifies everything.

I just have one more doubt.
I have a static file at “www.MyDomainWithCloudFlare.com/static/script.js
I believe this must be cached with cloud flare.

If I configure a worker for the route “www.MyDomainWithCloudFlare.com/static/script.js”, and in that worker I fetch “www.MyDomainWithCloudFlare.com/static/script.js”, will I get the cached copy or the from the origin? If I get it from origin how can I get it from the cache?

Fetch requests to your origin will continue to use CF’s cache, however each request will still be counted as a request for Workers billing, even if the resource is cached.

1 Like