Cloudflare IP Geolocation service is the fastest and easiest way to detect and identify the country of your users or visitors, for free.
In this guide, we will be showing you how easy it is to use Cloudflare IP Geolocation service to geolocate your users or visitors.
What is IP geolocation
Before we dive into the details, let’s briefly go through what is IP geolocation.
IP geolocation is the mapping of an IP address to the geographic location of the internet from the connected device. By geographically mapping the IP address, it provides you with location information such as the country, state, city, zip code, latitude/longitude, ISP, area code, and other information.KeyCDN
So basically it’s the process of determining a user’s country based on the IP address.
IP geolocation services
Luckily, you don’t have to figure this out by yourself. There are few ways you can do that, for free:
- GeoIP database like MaxMind’s GeoLite2 and install it on your server.
- IP geolocation API service.
- Cloudflare IP Geolocation service.
Having GeoIP database locally on your server incurs computational overhead as well as the need to constantly keep the database updated. IP geolocation API on the other hand requires extra network calls to get the results which is slower than having a local database.
As for Cloudflare IP Geolocation service, it doesn’t require maintaining a database and nor any extra network calls. The only requirement is that you need to configure your site to use Cloudflare.
Enable Cloudflare IP Geolocation
Assuming you have already signed up for Cloudflare, go the “Network” app tab and turn on “IP Geolocation“. It should, by default turned on.
Getting user’s country code
Once enabled, Cloudflare will add
CF-IPCountry to all requests made to your website with the country code to you in ISO 3166-1 Alpha 2 format.
So, all you have to do is to read
CF-IPCountry header in your backend to get the country code.
XX country code
Depending on the language and server you use, you might want to
For example in PHP, it’s called
$country = $_SERVER["HTTP_CF_IPCOUNTRY"]
In Node.js it is
let country = req.headers.get("cf-ipcountry")
Let us know if you found any other
CF-IPCountry header variants for other languages.