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
}
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
And finally below is a pure Javascript that parses Cloudflare output and extracts visitor's IP address and country.
// 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!
Top comments (1)
This solution will not work if the user is using an adblocker