Skip to content

Instantly share code, notes, and snippets.

@panoply
Last active November 19, 2018 05:52
Show Gist options
  • Save panoply/17bbb2ad080d032c68000304c51a2b51 to your computer and use it in GitHub Desktop.
Save panoply/17bbb2ad080d032c68000304c51a2b51 to your computer and use it in GitHub Desktop.
Cloudflare Client Side GeoIP

Cloudflare GeoIP (Client Side)

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.

Live Example

Flems

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