How to Detect User’s Country Using Cloudflare IP Geolocation

Cloudflare IP Geolocation service is the fastest and easiest way to detect and identify the country of your users or visitors, for free.
Get User's Country Using Cloudflare IP Geolocation Service

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:

  1. GeoIP database like MaxMind’s GeoLite2 and install it on your server.
  2. IP geolocation API service.
  3. 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.

Cloudflare IP Geolocation Service Settings
Cloudflare IP Geolocation Service Settings

That’s it.

Getting user’s country code

Once enabled, Cloudflare will add a HTTP header called 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

If for some reason Cloudflare unable to geolocate the IP of your users, the country code of XX will be returned.

Examples

Depending on the language and server you use, you might want to double check the exact header name for CF-IPCountry.

For example in PHP, it’s called HTTP_CF_IPCOUNTRY:

$country = $_SERVER["HTTP_CF_IPCOUNTRY"]

In Node.js it is cf-ipcountry:

let country = req.headers.get("cf-ipcountry")

Let us know if you found any other CF-IPCountry header variants for other languages.


Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply