"Inject" GeoIP info in page?


This may be a tricky one.
Is it possible (via an app or worker) to dynamically inject GeoIP info (maybe add a cookie header?) to a cached page?

I have a site with html pages that I want to be cached by CloudFlare. But now with GDPR I want to dynamically determine if I need to show the cookie compliance banner. Of course, I could always make another XHR to the server and determine the country from the HTTP_CF_IPCOUNTRY header, but I’d avoid an extra call if possible (I want to keep it as fast as possible).

I’m not to CF and I don’t know what the Apps and Workers are capable of, so can either of them do the following:

  1. read the HTTP_CF_IPCOUNTRY from the request
  2. get the cached html and either
    a. add a cookie header in the response or
    b. add some js code in the page itself, e.g.


Cloudflare has some example workers in their documentation and it occurs to me that the Custom responses that don’t hit origin servers worker could be used as a starting point. Since this request comes directly from Cloudflare’s edge and has no additional round-trip to your server it would probably load fast enough to not matter.

Alternatively if you really want everything in one single request, the worker could use a return fetch to change the request URL to modify the request to indicate EU vs NOT-EU and your server could generate the appropriate response either with or without the inline javascript.

I really prefer the the idea of returning the EU vs NOT-EU status right from the edge, even though it does technically require one additional request between the browser and the edge. Also this request should be something you can cache on the client side.

It is also possible someone more clever than me will have a better idea :slight_smile:


I would use JavaScript/Ajax. After page load, fetch via GET a Non-cached server page which processes the header and returns the data you want.
You can optimize this by storing the info in a cookie or session variable for subsequent page loads.
At least, that’s how I did it. :nerd_face:


Thanks guys. I’ll probably start with the straightforward Ajax method, which is easier to implement, and then I’ll investigate the worker method.


The nice thing is that the worker can end up answering the query your Ajax approach uses.