Skip to main content

Redirect visitors by country

Redirect visitors to region-specific content, storefronts, or legal pages using IPLocate’s IP geolocation API.

Client-side redirect (JavaScript)

// Redirect based on the visitor's country
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 === 'DE') {
window.location.href = '/de/';
} 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.

See our full list of API fields for more information.

Server-side example (Express)

import express from 'express';
import IPLocate from 'node-iplocate';

const app = express();
app.set('trust proxy', true);

const client = new IPLocate(process.env.IPLOCATE_API_KEY);

app.get('/', async (req, res) => {
const ip = req.ip;
const data = await client.lookup(ip);

if (data.country_code === 'FR') return res.redirect(302, '/fr/');
if (data.country_code === 'DE') return res.redirect(302, '/de/');
return res.send('Home');
});

Best practices

  • Cache responses and respect rate limits; see caching responses.
  • Avoid redirect loops by honoring a user “country override” preference.
  • Consider SEO: serve alternate content without redirecting search crawlers.