How to Auto-Detect User Country, State & City Without GPS? (Practical Implementation)
In modern web development, personalizing user experience often begins with understanding where your traffic originates. Whether you are automating currency selection, enforcing regional compliance (like GDPR or CCPA), or directing users to the nearest data center, geographic context is essential.
While the HTML5 Geolocation API exists, it requires explicit user consent and relies on GPS or Wi-Fi triangulation. For many backend processes—such as security logging, fraud detection, or initial page rendering—waiting for a user to click "Allow" is not viable. This is where IP Geolocation becomes the standard technical approach. This article explains how IP-based location detection works, its limitations, and how to implement it correctly using a production-ready IP intelligence API.

Understanding IP-to-Location Mapping
IP geolocation works by mapping an IP address (IPv4 or IPv6) to a physical location. Unlike GPS, which uses satellite signals, IP geolocation relies on a massive infrastructure of data registries and network routing information.
How it Works Internally
When a device connects to the internet, it is assigned an IP address by an Internet Service Provider (ISP). These IP addresses are distributed in blocks by Regional Internet Registries (RIRs) like ARIN (North America) or RIPE (Europe).
Geolocation providers aggregate data from several sources to build their mapping tables:
- RIR Data: Information on which ISP owns a specific block of IPs.
- BGP (Border Gateway Protocol) Feeds: Analyzing routing paths to determine the physical location of network infrastructure.
- Latency Measurements: Calculating the time it takes for a packet to travel between known nodes to estimate distance.
- User-Submitted Data: Information from weather apps or shipping sites where users have voluntarily provided both an IP and a zip code.
What “without GPS” really means
IP-based geolocation does not track physical devices. It infers location based on network topology and administrative data. This means:
- No device sensors are accessed
- No browser permissions are required
- Detection works equally well for backend-only systems
However, the inferred location represents the network egress point, not the user’s exact physical position.
Implementing IP Geolocation in Your Stack
To detect location server-side, you retrieve the client's IP address from the request headers and query a geolocation database or API.
Handling the Client IP
In a typical production environment, your application sits behind a load balancer or reverse proxy (like Nginx or Cloudflare). In these cases, the standard remote_addr will return the proxy's IP, not the user's. You must look for the X-Forwarded-For or CF-Connecting-IP headers.
API Request Example
Using a REST API is generally preferred over local database files for most SaaS applications because it offloads the burden of keeping the multi-gigabyte IP data files updated.
Here is a standard request using curl to retrieve location data:
curl -X GET "https://api.ip2geoapi.com/ip/37.203.37.108?key=YOUR_API_KEY"
The JSON Response Structure
{
"success": true,
"ip": "37.203.37.108",
"version": "ipv4",
"geo": {
"city": "Riga",
"country": "Latvia",
"countryCode": "LV",
"region": "Rīga",
"regionCode": "RIX",
"latitude": 56.9473,
"longitude": 24.0979,
"postalCode": "LV-1063",
"geonameId": 458258,
"accuracyRadius": 20,
"metroCode": null,
"continentName": "Europe",
"continentCode": "EU",
"isEuMember": true
},
"countryInfo": {
"name": "Latvia",
"alpha2Code": "LV",
"alpha3Code": "LVA",
"flag": "https://api.ip2geoapi.com/assets/flags/lv.svg",
"callingCodes": [
"371"
],
"currencies": [
{
"code": "EUR",
"name": "Euro",
"symbol": "€"
}
],
"languages": [
{
"iso639_1": "lv",
"iso639_2": "lav",
"name": "Latvian",
"nativeName": "latviešu valoda"
}
]
},
"timezoneInfo": {
"timezone": "Europe/Riga",
"utcOffsetSeconds": 7200,
"utcOffsetText": "+02:00",
"utcOffsetHours": 2,
"isDst": false,
"abbreviation": "GMT+2",
"localTime": "2026-01-16T07:22:12+02:00"
},
"network": {
"cidr": "37.203.37.0/24",
"prefixLen": 24,
"asn": 215373,
"asFormatted": "AS215373",
"asName": "Sabiedriba ar ierobezotu atbildibu DELSKA Latvia",
"isp": "Sabiedriba ar ierobezotu atbildibu DELSKA Latvia",
"organization": "Sabiedriba ar ierobezotu atbildibu DELSKA Latvia",
"connectionType": "Cable/DSL",
"mobile": {
"mcc": null,
"mnc": null
}
},
"asDetails": {
"asn": 215373,
"abuser_score": "0.0072 (Low)",
"descr": "DELSKA-C4, LV",
"country": "lv",
"active": true,
"org": "Sabiedriba ar ierobezotu atbildibu DELSKA Latvia",
"domain": "deac.eu",
"abuse": "[email protected]",
"type": "hosting",
"created": "2025-09-10",
"updated": "2025-09-10",
"rir": "RIPE"
},
"security": {
"isHosting": true,
"isProxy": false,
"proxyType": null,
"isVpn": false,
"vpnProvider": null,
"vpnProviderUrl": null,
"isTor": false,
"isAnonymous": true,
"trustScore": 65,
"riskLevel": "medium"
}
}
From a backend perspective, you can safely use:
countryCodefor regulatory logicregionCode or region for state-level rulescityfor UI personalization or analytics
latitude and longitude should be treated as approximate.
IPv4 vs IPv6 Considerations
Our geolocation APIs should support both IPv4 and IPv6.
| Aspect | IPv4 | IPv6 |
|---|---|---|
| Address space | Limited | Vast |
| Adoption | Universal | Rapidly growing |
| Geolocation quality | Mature | Improving but uneven |
| Mobile networks | Common | Increasingly common |
IPv6 geolocation accuracy can vary depending on the ISP. Some providers assign large IPv6 prefixes dynamically, which can reduce city-level precision. A robust IP intelligence API should handle both formats transparently.
Solving Challenges with ip2geoapi.com
Manually maintaining an IP database is a significant DevOps burden. IP ranges change ownership daily, and accuracy degrades quickly if your local data is even a week old.
This is where ip2geoapi.com provides a high-performance alternative. It offers a streamlined, low-latency API designed for high-throughput production environments.
Why Use ip2geoapi?
- High Precision: Accurate mapping for Country, State, City, and ASN data.
- Developer Friendly: Simple RESTful endpoints that return clean JSON, making integration into Node.js, Python, Go, or Ruby trivial.
- Generous Free Tier: To support developers and early-stage startups, the service offers 100,000 free requests per month. This allows you to scale your MVP or internal tools without immediate overhead.
- No Maintenance: The underlying data is updated continuously, ensuring you never make decisions based on stale IP records.
To get started, you can obtain a free API key and begin testing within minutes.
Python Implementation of IP-GEO API
Below is a clean, production-style Python example showing how to call the ip2geoapi API, handle errors, and parse fields from the JSON structure you shared.
This uses only the standard requests library and works for IPv4 and IPv6.
import requests
API_KEY = "YOUR_API_KEY"
IP_ADDRESS = "8.8.8.8" #get IP address of client first
URL = f"https://api.ip2geoapi.com/ip/{IP_ADDRESS}"
def lookup_ip(ip: str) -> dict:
params = {
"key": API_KEY
}
try:
response = requests.get(URL, params=params, timeout=30)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
raise RuntimeError(f"IP lookup failed: {e}")
if __name__ == "__main__":
data = lookup_ip(IP_ADDRESS)
if not data.get("success"):
raise RuntimeError("API returned success=false")
geo = data["geo"]
network = data["network"]
security = data["security"]
print("IP:", data["ip"])
print("Version:", data["version"])
print("Country:", geo["country"], f"({geo['countryCode']})")
print("Region:", geo["region"])
print("City:", geo["city"])
print("ISP:", network["isp"])
print("ASN:", network["asFormatted"])
print("VPN:", security["isVpn"])
print("Proxy:", security["isProxy"])
We have code examples in other languages. In thr above example, you have to derive the client IP on your own from the http request.
Common Pitfalls and Accuracy Limitations
While IP geolocation is highly effective, it is not a 1:1 replacement for GPS. Developers should be aware of the following technical constraints:
1. VPNs and Proxies
If a user is using a VPN, the IP detected will be that of the VPN exit node, not the user's home address. If your use case requires strictly verifying a user's physical presence (e.g., for regulated sports betting), you should check the isProxy or isVpn flags in the API response.
2. Mobile Networks
Mobile IPs are often backhauled. A user in a rural town might appear to be in a major city hundreds of miles away because that is where their mobile carrier’s gateway is located. However, if your sole purpose is to redirect users based on their country, such broad accuracy radius should not matter.
3. Precision vs. Accuracy
Never assume IP geolocation is accurate to the house or street level. It is generally accurate at the:
- Country level: 99% +
- State/Region level: 90% +
- City level: 70-85% (varies by country)
Performance and Security Considerations Caching Strategy To minimize latency and API costs, implement a caching layer. Since a user’s IP address rarely changes during a single session, you can cache the geolocation result in Redis or an in-memory store using the IP as the key. Set a Time-to-Live (TTL) of 24 hours to balance accuracy with performance.
Handling API Failures Always implement a fallback. If the geolocation API times out or returns an error, your application should default to a neutral experience (e.g., default to USD and English) rather than crashing.
try {
const locationData = await fetchGeoData(userIp);
applyLocalization(locationData);
} catch (error) {
console.error("Geo-detection failed, using defaults.");
useDefaultSettings();
}
Conclusion
Auto-detecting a user’s country, state, and city without GPS is a practical and widely adopted technique based on IP geolocation. It works across devices, requires no user permissions, and integrates cleanly into backend systems.
While IP-based detection has known accuracy limits — especially at the city level—it is reliable enough for pricing localization, compliance, security, and analytics when used correctly. Supporting both IPv4 and IPv6, handling proxies properly, and understanding edge cases are essential for accurate results.
With a simple HTTP API and a free usage tier, services like ip2geoapi.com make it straightforward to add IP-based location intelligence to modern applications without unnecessary complexity.