IP geolocation is one of the most-requested features in web apps. Here's how to add it to your project in 5 minutes using an API — no database to maintain, no MaxMind subscription.
What You Get from an IP
{
"ip": "203.0.113.42",
"country": "KR",
"country_name": "South Korea",
"city": "Seoul",
"region": "Seoul",
"lat": 37.5665,
"lon": 126.9780,
"timezone": "Asia/Seoul",
"isp": "Korea Telecom",
"is_vpn": false,
"is_datacenter": false
}
Basic Usage
// Get the visitor's location
async function getVisitorLocation(ip) {
const resp = await fetch(`https://api.lazy-mac.com/ip-geo/lookup?ip=${ip}`);
return resp.json();
}
// In an Express.js route
app.get('/content', async (req, res) => {
const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
const location = await getVisitorLocation(ip);
// Serve localized content
const content = getLocalizedContent(location.country);
res.json({ content, location: location.city });
});
Real Use Cases
1. Currency localization
const { country } = await getVisitorLocation(userIp);
const currency = COUNTRY_CURRENCY_MAP[country] || 'USD';
2. GDPR/PIPA compliance
const { country } = await getVisitorLocation(userIp);
if (['KR', 'GB', 'DE', 'FR'].includes(country)) {
showConsentBanner();
}
3. Content restrictions
const RESTRICTED_COUNTRIES = ['CN', 'IR', 'KP'];
if (RESTRICTED_COUNTRIES.includes(location.country)) {
return res.status(451).json({ error: 'Service not available in your region' });
}
4. Fraud detection
if (location.is_vpn || location.is_datacenter) {
flagForReview(transaction);
}
Cloudflare Workers Bonus
If you're on Cloudflare Workers, you get geolocation for free without any API call:
const country = request.cf?.country;
const city = request.cf?.city;
const timezone = request.cf?.timezone;
For non-Cloudflare backends: IP Geo API | Full store
Top comments (0)