How to detect clients country codes when using Cloudflare

How to detect clients country codes when using Cloudflare

When using Cloudflare, often people get anxious that analytics reports may get messed up because all traffic comes from Cloudflare CDN. It is especially true for reports relying on clients’ locations. Beyond analytics, some of the features that are specific for certain locations may also get messed up. But no need to panic at all. Cloudflare already, in fact since a very long time ago, has solved this problem. In this article, I cover how to detect clients’ country codes when using Cloudflare.

Enabling IP Geolocation feature on Cloudflare

Cloudflare offers a simple solution to get the client country code for all its customers, even those in the free tier. All you need to do is go to your Cloudflare dashboard under the Network section. You should see a switch called IP Geolocation enable that and save the changes.

How to detect clients country codes when using Cloudflare

After enabling that option, Cloudflare adds the HTTP_CF_IPCOUNTRY header that contains ISO 3166-1 Alpha 2 country code to each request.

Reading the header in the application

Since Cloudflare adds country codes to request headers, all left to do is to read the value and apply it whenever that’s necessary. It is a straightforward process. For the sake of completeness, I demonstrate examples of reading HTTP request headers in both Java and PHP.

Let’s start with Java one (my favorite),

private void printCountryCode(HttpServletRequest request) {
    String countryCode = request.getHeader("HTTP_CF_IPCOUNTRY");
    if (StringUtils.isNotBlank(countryCode)) {
        log.info("Country code: {}", countryCode)
    }
}

Keep note that the example relies on Servlet. It should work on any Spring, Quarkus based application. However, if you use a non-Servlet framework, i.e., Netty, the above code won’t work.

In PHP also you can read HTTP request headers as follows,

function print_client_country_code() {
    if (isset($_SERVER['HTTP_CF_IPCOUNTRY'])) {
        echo "Country code: {$_SERVER['HTTP_CF_IPCOUNTRY']}"
    }
}

It’s simpler than the Java one 🙂

That’s pretty much everything that you need to detect clients’ country codes when using Cloudflare. As you have seen Cloudflare does the heavy lifting and converts the IP address to location and add it to request headers.

Inline/featured images credits