Skip to content

Instantly share code, notes, and snippets.

@rubinchyk
Last active November 15, 2023 08:42
Show Gist options
  • Save rubinchyk/fde116cbd3a1454a1873e0e71b3ed439 to your computer and use it in GitHub Desktop.
Save rubinchyk/fde116cbd3a1454a1873e0e71b3ed439 to your computer and use it in GitHub Desktop.
[User location identification using Cloudflare] User location identification using Cloudflare

Also look here: https://www.geojs.io/ Example: https://get.geojs.io/v1/ip/country, https://get.geojs.io/v1/ip/geo.json

In Cloudflare Network -> IP Geolocation switch turn on Rules -> Page Rules -> sttcdn.site.com/* The most important and probably only one which can work: Rules -> Transform Rules -> Modify response header -> cf-ipcountry: Any name, All incoming requests, Set Dynamic - Header Name: X-User-Country - Value: ip.src.country

Domain should provide in response this headers: Access-Control-Allow-Origin: * Access-Control-Expose-Headers: X-User-Country

fetch('https://sttcdn.site.com/').then(response=>{
const country = response.headers.get('x-user-country');
const countryCodes = ['US', 'CA', 'JP', 'AU', 'SG', 'KR', 'TH', 'MY', 'NZ', 'BR', 'MX']
if (country && country.length === 2 && countryCodes.includes(country)) {
// Country in list
} else {
// Country not in list or no country value
}
}
).catch(error=>{
console.error('Error fetching data:', error);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment