This content originally appeared on DEV Community and was authored by Geoapify
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 | ![]() |
![]() |
Fast server-side personalization |
IP Geolocation API (Geoapify) | Country + city | ![]() |
![]() |
Universal use, flexible setups |
Browser Geolocation + Reverse | Very precise | ![]() |
![]() |
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!
This content originally appeared on DEV Community and was authored by Geoapify