Change website based on visitor’s country —using Javascript
In this example, we will show how you can present a country specific website to a visitor, based on their physical location, using an IP Geolocation service.
The example relies on the free tier which is great for development and testing, but if you own a public facing website, please sign-up for a subscription for uninterrupted service here : ipapi.co/pricing
Let’s say you have a couple of country specific websites e.g. Site-X, Site-Y and Site-Z for visitors from countries X, Y and Z respectively. The pseudo code to redirect the visitors to these websites would be :
1. Get visitor's country
2. If country is 'X', go to Site-X
3. If country is 'Y', go to Site-Y
4. Else, go to Site-Z
You need to place this code in one of your websites, say Site-X (the default choice). Without further delay, here’s an example in plain Javascript (no jQuery etc. libraries required).
/*
The default country is US and the default site is google.com
The code below is placed on the default site. The other site where you want to send visitors from the rest of the world is google.co.uk
*/var defaultCountry = ‘US’;
var defaultSite = ‘https://google.com';
var otherSite = ‘https://google.co.uk';fetch(‘https://ipapi.co/country/')
.then(response => {
if (response.ok) {
return response.text();
} else {
throw new Error(‘HTTP Error ‘ + response.status);
}
})
.then(country => {
if (country == defaultCountry) {
// No action needed - already on the default site
console.log(‘Already on default site’);
} else {
// Redirect rest of the world
console.log(‘Redirecting to country specific website’);
window.location = otherSite;
}
})
.catch(function(error) {
// Network error
// Script blocked by browser extension
// 429 error (too many requests)
console.log(error);
});