Clean the subdomain and insert substitute the main domain in Worker


Here is my concept: Distribute incoming request based on the Geolocation of the user and serve data from the nearest server located nearby. I do not want to use fetch method and use Response/redirect. I want to achieve this with following steps:

async function Redirect(request) {
const country_code = request.headers.get(‘cf-ipcountry’)
const serverLocation = new Map([ [“NL”, ‘servereurope’], [“US”, ‘serverusa’], ])
const cdnserver = serverLocation.get(country_code)
if (cdnserver)
const url = new URL(request.url)
const maindomain = “.” + url.hostname
const path = url.pathname
const protocol = url.protocol
const destinationDomain = protocol + “//” + cdnserver + maindomain + path
return Response.redirect(destinationDomain, 301)

I have following problems:

I cannot clean the url.hostname to contain the domainname only. Any subdomain part should be removed otherwise it will not work. How could I achieve this?

The above does not check if the url.hostname is the domainname itself or if it was generated through the worker. If it generated, then it contains subdomain. So, that should be either a bypassed or cleaned and substituted again.

I do not want to use fetch and use redirect. I cannot get the Response to give any output.

Any suggestion?

Why not use the Cloudflare Load Balancer with the Traffic Steering add-on?

Hello Michael,

Thanks for your suggestion, as an alternative. I am using a free account for my small project. When it grows, I will remember your suggestion.
But now, I need to make it work like I described in my concept above. The coding is partially complete. It does not work.