Want to redirect users based on their country — for example, sending EU users to a GDPR-compliant site, or US visitors to a local storefront? Here's how to do it quickly and reliably using IPLocate's geolocation API.
IPLocate provides fast, accurate IP geolocation and company, hosting, and threat data. It's built for developers and used in production at scale. You can sign up for a free API key here — no credit card required.
In this post, we'll walk through how to:
- Redirect users by country using JavaScript and IPLocate
- Exclude bots to save API calls
- Cache results to avoid repeated lookups
Redirect Users by Country with JavaScript
Here’s a quick, client-side example using fetch
to call the IPLocate API and redirect users by their country code:
fetch('https://iplocate.io/api/lookup/?apikey=YOUR_API_KEY')
.then(res => res.json())
.then(data => {
if (data.country_code === 'FR') {
window.location.href = '/fr/';
} else if (data.country_code === 'US') {
window.location.href = '/us/';
}
});
This looks up the IP address of the current user (no IP needed in the request — IPLocate will automatically use the user's IP). You can redirect users based on any of the fields in the API response like country_code
, continent
, is_eu
, or even more advanced data like whether the IP is a VPN or proxy.
Want to check what data is available? See the full API field reference here.
Avoid Bots (and Save Your API Quota)
To avoid wasting API requests on search engine bots, you can exclude obvious crawlers using the navigator.userAgent
string:
if (!navigator.userAgent.match(/bot|spider/i)) {
fetch('https://iplocate.io/api/lookup/?apikey=YOUR_API_KEY')
.then(res => res.json())
.then(data => {
if (data.country_code === 'DE') {
window.location.href = '/de/';
}
});
}
This simple regex will skip known bots and spiders, so you make the most of your API quota.
Cache Results to Reduce API Usage
Since the user’s IP usually doesn’t change often, you can cache their geolocation result in localStorage
to avoid repeated API requests:
const cached = localStorage.getItem('userCountry');
if (cached) {
maybeRedirect(cached);
} else if (!navigator.userAgent.match(/bot|spider/i)) {
fetch('https://iplocate.io/api/lookup/?apikey=YOUR_API_KEY')
.then(res => res.json())
.then(data => {
localStorage.setItem('userCountry', data.country_code);
maybeRedirect(data.country_code);
});
}
function maybeRedirect(country) {
if (country === 'AU') {
window.location.href = '/au/';
}
}
This ensures that each visitor only triggers one API call per session (or per visit, depending on how long you store the result).
Want to get started? Sign up for a free API key here and check out the full documentation for more fields, plans, and usage examples.