Run worker only for US visitors

Hi,

I want to run a worker only for GET requests from US visitors. Will the following code work? The actual async function (not included here) doesn’t have any reference to country or headers. I have enabled “IP geolocation” in the network tab.

addEventListener(‘fetch’, event => {
event.passThroughOnException()
if(event.request.headers.get(“cf-ipcountry”) === ‘US’ && event.request.method === ‘GET’) {
event.respondWith(handle(event.request))
}
})

What exactly do you mean? Do you just not want to run a certain part of your worker for visitors from the US or avoid the entire worker from being run? In the latter case, that would not be possible. At this point the worker will have already started running. Currently it is not possible to selectively run a worker.

I understand the worker has started to run. I meant I don’t want the code in the async function to run for non-US visitors.

So for non-US visitors, the worker should have absolutely zero impact, other than the usage in my account, of course.

In that case your approach should work (not even sure if you need passThroughOnException).

You dont even need to access the headers, the country should be in cf.

if (event.request.cf.country == 'US' && event.request.method == 'GET')

Thanks! Would the performance be better if I don’t access the headers and get the country directly from CF?

I dont think this is in any way performance relevant.

Got it, thanks!