Tutorial

IP geolocation in JavaScript, Python and PHP

Find the visitor's real IP address, look it up and cache the result: complete examples for Node.js, Python and PHP.

Updated October 1, 2026 ยท 1 min read

Step 1: the real client IP

SetupHeader
CloudflareCF-Connecting-IP
nginx / most load balancersfirst value of X-Forwarded-For (or X-Real-IP)
No proxythe socket address

Only trust these headers if the request really came through your proxy; otherwise clients can fake them.

Node.js

const cache = new Map();

async function geolocate(ip) {
  if (cache.has(ip)) return cache.get(ip);
  const res = await fetch(`https://api.ipbase.com/v2/info?ip=${encodeURIComponent(ip)}`, {
    headers: { apikey: process.env.IPBASE_KEY },
  });
  const { data } = await res.json();
  const result = { country: data.location.country.alpha2, city: data.location.city?.name, isp: data.connection?.isp };
  cache.set(ip, result);
  return result;
}

Python

import os, requests
from functools import lru_cache

@lru_cache(maxsize=10_000)
def geolocate(ip: str) -> dict:
    res = requests.get("https://api.ipbase.com/v2/info", params={"ip": ip},
                       headers={"apikey": os.environ["IPBASE_KEY"]}, timeout=5)
    res.raise_for_status()
    loc = res.json()["data"]["location"]
    return {"country": loc["country"]["alpha2"], "city": (loc.get("city") or {}).get("name")}

PHP

function geolocate(string $ip): array
{
    $ch = curl_init('https://api.ipbase.com/v2/info?ip=' . urlencode($ip));
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['apikey: ' . getenv('IPBASE_KEY')], CURLOPT_TIMEOUT => 5]);
    $data = json_decode(curl_exec($ch), true)['data'];
    curl_close($ch);
    return ['country' => $data['location']['country']['alpha2'], 'city' => $data['location']['city']['name'] ?? null];
}

Tips

Frequently asked questions

Can I get the user's location in the browser without an API?

The browser's Geolocation API gives a precise position, but only after the user agrees. IP geolocation works without a prompt and is precise enough for country, language and currency defaults.

Why do I always see the same IP address in my logs?

Your app is behind a proxy or load balancer. Read the client IP from the header it sets (X-Forwarded-For, CF-Connecting-IP, X-Real-IP) and only trust that header from your own proxies.

IP geolocation API

Get this data in your app

ipbase returns location, ISP, ASN, time zone and security flags (VPN, proxy, Tor, data center) for any IPv4 or IPv6 address, up to 100 addresses per request.

150 free requests every month. No credit card required.

GET https://api.ipbase.com/v2/info?ip=1.1.1.1

{
  "data": {
    "ip": "1.1.1.1",
    "type": "v4",
    "connection": {
      "asn": 13335,
      "organization": "APNIC and Cloudflare DNS Resolver project",
      "isp": "Cloudflare, Inc",
      "range": "1.1.1.0/24"
    },
    "location": {
      "country": { "alpha2": "AU", "name": "Australia" },
      "zip": "4000"
    },
    "security": { "is_vpn": false, "is_tor": false, "threat_score": 0 }
  }
}

Keep reading

Start using the IP Geolocation API for free today!

Get 150 requests / month for free