Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Cloudflare's HTTP_CF_IPCOUNTRY header with javascript?

There are many SO questions how to get http headers with javascript, but for some reason they don't show up HTTP_CF_IPCOUNTRY header.

If I try to do with php echo $_SERVER["HTTP_CF_IPCOUNTRY"];, it works, so CF is working just fine.

Is it possible to get this header with javascript?

like image 617
Badr Hari Avatar asked Sep 08 '15 10:09

Badr Hari


4 Answers

@Quentin's answer stands correct and holds true for any javascript client trying to access server header's.

However, since this question is specific to Cloudlfare and specific to getting the 2 letter country ISO normally in the HTTP_CF_IPCOUNTRY header, I believe I have a work-around that best befits the question asked.

Below is a code excerpt that I use on my frontend Ember App, sitting behind Cloudflare... and varnish... and fastboot...

function parseTrace(url){
    let trace = [];
    $.ajax(url,
        {
            success: function(response){
                let lines = response.split('\n');
                let keyValue;

                lines.forEach(function(line){
                    keyValue = line.split('=');
                    trace[keyValue[0]] = decodeURIComponent(keyValue[1] || '');

                    if(keyValue[0] === 'loc' && trace['loc'] !== 'XX'){
                        alert(trace['loc']);
                    }

                    if(keyValue[0] === 'ip'){
                        alert(trace['ip']);
                    }

                });

                return trace;
            },
            error: function(){
                return trace;
            }
        }
    );
};

let cfTrace = parseTrace('/cdn-cgi/trace');

The performance is really really great, don't be afraid to call this function even before you call other APIs or functions. I have found it to be as quick or sometimes even quicker than retrieving static resources from Cloudflare's cache. You can run a profile on Pingdom to confirm this.

like image 182
Don Omondi Avatar answered Nov 08 '22 21:11

Don Omondi


Assuming you are talking about client side JavaScript: no, it isn't possible.

  1. The browser makes an HTTP request to the server.
  2. The server notices what IP address the request came from
  3. The server looks up that IP address in a database and finds the matching country
  4. The server passes that country to PHP

The data never even goes near the browser.

For JavaScript to access it, you would need to read it with server side code and then put it in a response back to the browser.

like image 9
Quentin Avatar answered Nov 08 '22 20:11

Quentin


fetch('https://cloudflare-quic.com/b/headers').then(res=>res.json()).then(data=>{console.log(data.headers['Cf-Ipcountry'])})

Reference:

https://cloudflare-quic.com/b

https://cloudflare-quic.com/b/headers

Useful Links:

https://www.cloudflare.com/cdn-cgi/trace

https://github.com/fawazahmed0/cloudflare-trace-api

like image 8
Fawaz Ahmed Avatar answered Nov 08 '22 21:11

Fawaz Ahmed


Yes you have to hit the server - but it doesn't have to be YOUR server.

I have a shopping cart where pretty much everything is cached by Cloudflare - so I felt it would be stupid to go to MY server to get just the countrycode.

Instead I am using a webworker on Cloudflare (additional charges):

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  
  var countryCode = request.headers.get('CF-IPCountry');
  
  return new Response(
    
    JSON.stringify({ countryCode }),

    { headers: {
      "Content-Type": "application/json"
    }});
}

You can map this script to a route such as /api/countrycode and then when your client makes an HTTP request it will return essentially instantly (for me it's about 10ms).

 /api/countrycode
 {
    "countryCode": "US"
 }

Couple additional things:

  • You can't use webworkers on all service levels
  • It would be best to deploy an actual webservice on the same URL as a backup (if webworkers aren't enabled or supported or for during development)
  • There are charges but they should be neglibible
  • It seems like there's a new feature where you can map a single path to a single script. That's what I am doing here. I think this used to be an enterprise only feature but it's now available to me so that's great.
  • Don't forget that it may be T1 for TOR network

Since I wrote this they've exposed more properties on Request.cf - even on lower priced plans:

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

You can now get city, region and even longitude and latitude, without having to use a geo lookup database.

like image 5
Simon_Weaver Avatar answered Nov 08 '22 21:11

Simon_Weaver