Get users Country / IP using Javascript and Cloudflare and store in cookie

Posted by: Alex on November 5, 2020

Are you looking to have data on your users country they’re visiting from, IP (or more)? Then the below solution will allow just that, though only if your site is using Cloudflare.

After lots of trial and error I found a solution to get the users country, as well as IP and further info and store it in a cookie.

This is particularly useful if you are implementing cookie banners on your site, as only certain countries require these banners to be shown.

Pro’s:

  • Very fast
  • Unlimited lookups

Prerequisite’s / Con’s:

Your site must be using:

  • CloudFlare
  • jQuery

The JavaScript:

function parseCFTrace(url) {
  let trace = [];
  jQuery.ajax(url, {
    success: function (response) {
      let lines = response.split("\n");
      let keyValue;
      lines.forEach(function (line) {
        keyValue = line.split("=");
        trace[keyValue[0]] = decodeURIComponent(keyValue[1] || "");

        if (keyValue[0] === "loc" && trace["loc"] !== "XX") {
          var date = new Date();
          date.setTime(date.getTime() + 365 * 24 * 60 * 60 * 1000);
          var expires = "; expires=" + date.toGMTString();
          document.cookie =
            "countryCookie" + "=" + trace["loc"] + expires + "; path=/";
        }
      });

      return trace;
    },
    error: function () {
      return trace;
    },
  });
}

let CFcountryLookup = parseCFTrace("/cdn-cgi/trace");

Note:

You’ll probably want to add some kind of if/else check to see if the users cookie has already been set, we don’t need to check their country and set the cookie one very visit. I suggest doing this with PHP before echo‘ing out the above JS code.

How it works

This piece of javascript will dynamically make a call to the Cloudflare IP and retrieve some information about the users visit, in total we have access to the following dataset, most notably/useful are “ip” and “loc” (location).
We then set a cookie called “countryCookie” with the ISO 2 letter version of their country, that will last for 1 year.

0: "fl"
1: "h"
2: "ip"
3: "ts"
4: "visit_scheme"
5: "uag"
6: "colo"
7: "http"
8: "loc"
9: "tls"
10: "sni"
11: "warp"
12: "gateway"