Redirect based on Country using Workers

Hello,

I am trying to set up Country-based redirection using Cloudflare Workers. I have followed the instructions on: Country-based redirection using Cloudflare | Geo-based redirection using Cloudflare - YouTube

Unfortunately, however, my site does not redirect. I am visiting from an incognito browser from Greece but it still drives me towards /en instead of /gr
Here is the code I am using:

/**

/**

if (country != null && country in countryMap) {
const url = countryMap[country];
return Response.redirect(url);
} else {
return fetch(request);
}
}

addEventListener(‘fetch’, event => {
event.respondWith(redirect(event.request));
});

Clearly, abc12vb.com is not my site, but I used it because I would rather prefer that my site is not indexed in google via the forum. Apart from the “abc12vb” part, everything else is exactly the same.

I would very much appreciate your help
Best Wishes,
Konstantinos

One thing to check is that you have IP geolocation enabled under the Network section of the relevant domain:

https://dash.cloudflare.com/?to=/:zone/network

I’m not 100% certain you need this, but worth trying.

If you have the worker deployed to a route and it still isn’t working when you visit a URL matching that route, then it’s best to start debugging:

https://developers.cloudflare.com/workers/learning/debugging-workers/

Hello Simon,

and thanks for trying to help. Yes, the IP geolocation is activated under the Networks tab. Also, yes it is deployed to a route - as it should be.

I will give my best to debug this, but I am not certain I can achieve my goal. Is there any other issue that may be causing this?
Thanks

One thing I forgot is that the request.cf object doesn’t actually exist in the playground or dashboard editor:

The request.cf object is not available in the Cloudflare Workers dashboard or Playground preview editor.

Source: https://developers.cloudflare.com/workers/runtime-apis/request/

So to debug, you’ll want to use wrangler tail or log, or classic old print debugging by outputting things to the response. Primarily, you need to understand what request.cf.country is when you make your request and see the unexpected result.

Thanks a lot for your help! Highly appreciated it.

Hello Simon,

this post has been also raised by a member of our team. Please see here:
https://community.cloudflare.com/t/cloudflare-not-working-properly/393450?fbclid=IwAR3exI7aW3Tp78FYfGRdoDz4ZnC7XdkpxP0pGGoSUpkvtkWbQIJjPNUJ-pM

It gives more details on the issue we are facing and we would love to see it being resolved asap. On this basis, I would very much appreciate your thoughts and possible contribution.

Thanks a lot once more.

This reminds me on a topic here, not sure if the same case?:

Could below YouTube video help a bit, maybe?:

1 Like