Personalizing your website based on a visitor’s country can improve user experience, help with compliance (like GDPR or content licensing), and boost marketing effectiveness.
If you only need to know which country a user is visiting from — and not their exact address — there are a few lightweight and privacy-friendly methods available.
In this article, we’ll compare three reliable approaches:
- Using built-in CDN headers (like Cloudflare, Fastly, AWS CloudFront)
- Calling an IP Geolocation API (e.g. Geoapify IP Geolocation)
- Falling back to the browser’s Geolocation API + reverse geocoding
Each has its pros and cons — let’s dive in!
Method 1. Detect Country with CDN Headers
If your site is hosted behind a CDN (Content Delivery Network), you may already have access to a country code in the HTTP headers — no extra API call needed.
Examples by provider:
CDN / Provider | Header name | Example value | Docs |
---|---|---|---|
Cloudflare | CF-IPCountry |
US |
Docs |
AWS CloudFront | CloudFront-Viewer-Country |
DE |
Docs |
Fastly | Fastly-Geo-Country-Code |
FR |
Docs |
Akamai | X-Akamai-Edgescape |
IN |
Docs |
Sample header (Cloudflare):
CF-IPCountry: US
How it works:
- The CDN detects the user’s IP at the edge.
- It injects the ISO country code into the request headers.
- Your backend can read the header and adjust the response (e.g., show localized content or redirect).
Pros:
- ⚡ Very fast (processed at the edge)
- 🛡️ Privacy-friendly (no extra user data needed)
- 💰 Free on most CDN plans
Cons:
- You need to use a CDN that supports geo headers
- Works best with server-side rendering (headers aren’t directly accessible from frontend JavaScript)
- Accuracy depends on the CDN’s IP database
📌 Best for: Edge personalization, geo-routing, or country-specific redirects.
Method 2. Detect Country with an IP Geolocation API
If you want a solution that works anywhere (with or without a CDN) and is easy to integrate on server or client, use an IP Geolocation API. The service looks up the requester’s public IP and returns metadata such as country, ISO code, timezone, and more.
Geoapify (recommended)
- Docs: Geoapify IP Geolocation
- Playground: Try it online
- Pricing: Generous free tier — 3000 requests/day
Request:
GET https://api.geoapify.com/v1/ipinfo?apiKey=YOUR_API_KEY
Sample response:
{
"ip": "93.109.164.24",
"city": {
"name": "Nicosia",
"names": { "en": "Nicosia" }
},
"continent": {
"code": "EU",
"name": "Europe",
"names": { "en": "Europe", "fr": "Europe", "ru": "Европа" }
},
"country": {
"iso_code": "CY",
"name": "Cyprus",
"name_native": "Κύπρος",
"capital": "Nicosia",
"currency": "EUR",
"flag": "🇨🇾",
"languages": [
{ "iso_code": "el", "name": "Greek", "name_native": "Ελληνικά" },
{ "iso_code": "tr", "name": "Turkish", "name_native": "Türkçe" }
]
},
"location": { "latitude": 35.17284, "longitude": 33.35397 }
}
Minimal examples
Node.js (server-side)
import fetch from "node-fetch";
export async function detectCountry(req, res) {
const apiKey = process.env.GEOAPIFY_KEY;
const url = `https://api.geoapify.com/v1/ipinfo?apiKey=${apiKey}`;
const r = await fetch(url);
const data = await r.json();
const country = data?.country?.name || "Unknown";
const flag = data?.country?.flag || "";
res.json({ country, flag, ip: data?.ip });
}
Browser (client-side)
Tip: Prefer server-side to avoid exposing your API key.
If you must run on the client, proxy the request through your backend.
// client -> your backend endpoint that calls Geoapify securely
fetch(`https://api.geoapify.com/v1/ipinfo?apiKey=${apiKey}`)
.then(r => r.json())
.then(data => {
document.documentElement.setAttribute("Country code: ", data.country.iso_code);
// toggle UI, load translations, etc.
});
Alternatives
(Feature sets, pricing, and ToS vary — check commercial usage terms.)
Pros
- 🧰 Works in any architecture (SSR, serverless, classic servers)
- 🌍 Rich metadata beyond country (city, timezone, languages, currency)
- 🔒 Privacy-friendly (IP lookup only; no user prompt)
Cons
- 🌐 Adds one network call (usually sub-200ms)
- 💳 Higher volumes may require a paid plan
Best practices
- Cache results per IP (e.g., 5–30 minutes) to cut latency and cost.
-
Fallback logic: If API fails, default to a safe locale (e.g.,
en-US
). - GDPR awareness: Avoid storing raw IPs unless necessary; log only the derived country when possible.
Method 3. Detect Country with Browser Geolocation + Reverse Geocoding
Another option is to use the browser’s Geolocation API, which gives you precise coordinates. To get the country, you’ll then need a reverse geocoding API.
Step 1: Get coordinates (requires user permission)
navigator.geolocation.getCurrentPosition(
(pos) => {
const { latitude, longitude } = pos.coords;
console.log(latitude, longitude);
},
(err) => {
console.error("User denied or unavailable:", err);
}
);
When called, the browser will ask the user for permission:
“This site wants to know your location.”
Step 2: Reverse geocode the coordinates
With Geoapify Reverse Geocoding API:
GET https://api.geoapify.com/v1/geocode/reverse?lat=35.17284&lon=33.35397&apiKey=YOUR_API_KEY
Sample response (shortened):
{
"features": [
{
"properties": {
"country": "Cyprus",
"country_code": "CY"
}
}
]
}
Pros
- 📍 Very accurate (uses GPS/WiFi/cell tower)
- 🌍 Works well for apps that need exact position (maps, delivery, nearby places)
Cons
- 🌐 Adds an extra network call (usually sub-200ms)
- ❌ Requires user permission (many will reject)
- ⚙️ Needs an additional reverse geocoding API call
📌 Best for: map applications, location-based services, check-ins, deliveries.
🧠 Comparison & Wrap-Up
We’ve looked at three main ways to detect a user’s country:
Method | Accuracy | User Consent | Extra API Call | Best For |
---|---|---|---|---|
CDN Headers (Cloudflare, etc.) | Country only | ✅ Not required | ❌ No | Fast server-side personalization |
IP Geolocation API (Geoapify) | Country + city | ✅ Not required | ✅ Yes | Universal use, flexible setups |
Browser Geolocation + Reverse | Very precise | ⚠️ Required | ✅ Yes | Maps, location-based applications |
Detecting a user’s country doesn’t have to be complicated. Each method has its place — the best choice depends on your app’s needs for speed, privacy, and accuracy.
🚀 Ready to try Geoapify?
👩💻 How are you handling country detection in your projects?
Drop a comment — I’d love to hear your approach or challenges!
Top comments (0)