Rewrite HTML based on CF Country Code

I have searched around quite a bit for examples or to see if this is possible, and even asked some developers but haven’t really found an answer. I would like to rewrite a body class or even add a body class, and potentially replace certain attributes depending on the country code using workers.

The idea is to have it change and everything be in place before being viewed in the browser without any flash or change of imagery. I’m not an overly experienced developer so there may be another way to do this, but my goal is to seamlessly display background graphics based on location while page caching.

I’ve searched high and low and can’t find anything so figured I’d put it to the community to see if it’s possible and if someone can point me in the direction to help with the worker script.

I’d probably do this server side, with the CF-IPCountry header.

If you really want to go the Worker route you can check out https://developers.cloudflare.com/workers/reference/apis/html-rewriter/ along with request.cf.country.

Yes, that’s what we do at the moment. However it prevents html cache as euro visitors could see a cached version from America and so on.

In that case you will have to go with Worker approach.

That was my question, is it something that can be done with workers, altering html etc before page load etc and is there any direction you could point me in to get the script put together

I already addressed that in my first response however :wink:

Oh, yes you did, missed that. Do you know a place to find or hire developers who are familiar with workers.

You could try freelancer.com, though that place is not specifically Worker related, but the pure Worker code should be pretty straightforward based on plenty of examples around and the task specific code will be plain JavaScript.

Overall, it shouldnt be too difficult for a developer who remotely knows JavaScript is capable of reading the documentation :slight_smile:.

Thanks again, you’ve been a great help

If you want to you can check out https://www.npmjs.com/package/cloudworker-proxy
It has ready made modules that you can configure to rewrite the body depending on the geo-header from cloudflare.

1 Like