DEV Community

Dmitry Narizhnyhkh
Dmitry Narizhnyhkh

Posted on β€’ Originally published at blog.dataflowkit.com on

4 1

πŸ“ How to detect the location of your website's users with Javascript for free?

How to detect the location of your website's users with Javascript for free?

Most websites display the same content for all visitors β€”no matter what they're searching for or how they got there.

But people who visit your web site have different purposes. Some want to buy something, others doing research. And some might be trying to find an exit as they don't know why they are there.

Why should I change website content based on visitor location?

Showing content in different languages for people from different countries would be a good idea.

You can pick up the user's location and show prices in one's local currency. This way, your visitors never have to look up exchange rates. In most cases, they finish their purchases. Also, you can show delivery times based on a visitor's location.

How about showing people ads relevant to their location? It seems like an obvious idea, and it works well. With location targeting campaigns, you can increase your store visits.

Providing personalized content leads to more sales.


We've recently published a web site with free COVID-19 live stats widgets. These widgets show information local to a visitor depending on one's location.

Check them out. Do widgets show your country statistics?

How to detect your website visitor location?

There are several ways to do that :

  • Geolocation API
  • IP Geolocation API
  • Use Cloudflare tracing endpoint for free

Geolocation

The geolocation API allows a web page’s visitor to share their location with you. A prompt is shown to the user, asking them if they’d like to share their location with your site. The output from the code gives us the coordinates.

{
  "location": {
    "lat": 33.3632256,
    "lng": -117.0874871
  },
  "accuracy": 20
}
Enter fullscreen mode Exit fullscreen mode

In case of negative response you have no way to get the user's location.

IP Geolocation APIs

Another way to get visitor's location is by using paid services from the list of APIs listed at IP Geolocation APIs.


Cloudflare trace endpoint

I'm going to show you how to identify user's location for free!

Cloudflare serves tracing pages on every site hosted on their domain at /cdn-cgi/trace endpoint.

After sending a request to https://www.cloudflare.com/cdn-cgi/trace an output should look somewhat like this:

fl=xxxxx
h=www.cloudflare.com
ip=xxx.xxx.xxx.xxx
ts=1589224733.208
visit_scheme=https
uag=Mozilla/5.0 ...
colo=PRG
http=http/2
loc=SK
tls=TLSv1.3
sni=plaintext
warp=off
Enter fullscreen mode Exit fullscreen mode

And finally below is a pure Javascript that parses Cloudflare output and extracts visitor's IP address and country.


//regular expressions to extract IP and country values
const countryCodeExpression = /loc=([\w]{2})/;
const userIPExpression = /ip=([\w\.]+)/;

//automatic country determination.
function initCountry() {
    return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest();
        xhr.timeout = 3000;
        xhr.onreadystatechange = function () {
            if (this.readyState == 4) {
                if (this.status == 200) {
                    countryCode = countryCodeExpression.exec(this.responseText)
                    ip = userIPExpression.exec(this.responseText)
                    if (countryCode === null || countryCode[1] === '' ||
                        ip === null || ip[1] === '') {
                        reject('IP/Country code detection failed');
                    }
                    let result = {
                        "countryCode": countryCode[1],
                        "IP": ip[1]
                    };
                    resolve(result)
                } else {
                    reject(xhr.status)
                }
            }
        }
        xhr.ontimeout = function () {
            reject('timeout')
        }
        xhr.open('GET', 'https://www.cloudflare.com/cdn-cgi/trace', true);
        xhr.send();
    });
}
Enter fullscreen mode Exit fullscreen mode
Identify visitor's location.
// Call `initCountry` function 
initCountry().then(result => console.log(JSON.stringify(result))).catch(e => console.log(e))

// Result
{"countryCode":"SK","IP":"xxx.xxx.xxx.xxx"}
Enter fullscreen mode Exit fullscreen mode

That's all. Now you can display dynamic content based on visitor IP address and geolocation.

Thanks for reading!

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (1)

Collapse
 
programmermarvin profile image
Marvin β€’

This solution will not work if the user is using an adblocker

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more