📍 How to detect the location of your website's users with Javascript for free?
Tags: geolocation, javascript, webdev, showdev
Published: 2020-05-21 19:36:17

---
title: 📍 How to detect the location of your website's users with Javascript for free?
published: true
date: 2020-05-11 23:16:33 UTC
tags: geolocation,javascript, webdev, showdev
canonical_url: https://blog.dataflowkit.com/determine-location-of-users/
---

 ![How to detect the location of your website's users with Javascript for free?](https://images.unsplash.com/photo-1526778548025-fa2f459cd5c1?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=2000&fit=max&ixid=eyJhcHBfaWQiOjExNzczfQ)

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](https://covid-19.dataflowkit.com) 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](https://developers.google.com/maps/documentation/geolocation/intro)  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.

```json
{
  "location": {
    "lat": 33.3632256,
    "lng": -117.0874871
  },
  "accuracy": 20
}
```

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](https://rapidapi.com/blog/ip-geolocation-api/).

* * *

## 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`](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
```

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

```javascript

//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();
    });
}
```
<figcaption>Identify visitor's location.</figcaption>
```javascript
// Call `initCountry` function 
initCountry().then(result => console.log(JSON.stringify(result))).catch(e => console.log(e))

// Result
{"countryCode":"SK","IP":"xxx.xxx.xxx.xxx"}
```

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

Thanks for reading!