Cloudflare geolocates your visitors and add their country code to your header. If you only have client side access you cannot access this header value but you can query the /cdn-cgi/trace
and grab the visitors country code. This code snippet is using the m.request
API which is apart of the Mithril.js framework Core API but this will also work with a basic vanilla XHR request.
Last active
November 19, 2018 05:52
-
-
Save panoply/17bbb2ad080d032c68000304c51a2b51 to your computer and use it in GitHub Desktop.
Cloudflare Client Side GeoIP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const geoip = { | |
code: null, | |
getCode: () => m.request({ | |
url: 'https://flems.io/cdn-cgi/trace', | |
deserialize: data => data.split('\n') | |
}).then((data) => { | |
const value = data.map((line) => line.split('=')) | |
const code = value.filter((line) => line[0] === 'loc') | |
geoip.code = code[0][1] !== 'XX' && code[0][1] | |
}) | |
} | |
/* Log */ | |
console.log(geoip.code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment