Get Cloudflare geolocation data client side

Cloudflare provides a very handy HTTP Header called `CF-IPCountry` which you can use to detect your users’ geolocation. You can read more about that here (https://support.cloudflare.com/hc/en-us/articles/200168236-Configuring-Cloudflare-IP-Geolocation)


Now, most people recommend creating an ajax request to get that geolocation data clientside as the header is only available from Cloudflare => Server not from Cloudflare => Client. This is all well and good however this can cause a fair bit of noise on a busy site as this request needs to be uncached.

Recently I was pointed to what might be a little hack where you can actually use Cloudflares `cdn-cgi/trace` URL to pull through your geolocation data.

    return axios
        .get('https://cloudflare.com/cdn-cgi/trace')
        .then({data} => {
            let country_code = 'XX';
            let lines = data.split('\n');
            let keyValue;

            lines.forEach(line => {
                keyValue = line.split('=');
                if (keyValue[0] === 'loc') {
                    country_code = decodeURIComponent(keyValue[1] || '');
                }
            });
            return country_code;
        })
        .catch(error => {
            return 'XX';
        });

What y’all thought

Have something to say?