{
"ip": "203.0.113.42",
"city": "London",
"region": "England",
"country": "GB"
}A real IP geolocation API response - this is what you'll parse on every page load.
Showing a visitor their own city is one of the oldest, simplest and most effective personalisation tricks on the web. A line like "Hello, London!", or a CTA that swaps in the visitor's nearest store, lifts conversion rates because it instantly proves the page knows something specific about the person reading it.
The technique behind it is IP geolocation: you take the visitor's public IP address, pass it to a lookup service, and get back a city, region and country in milliseconds. This guide walks through every part of doing it well in 2026 - the APIs, the code, the accuracy caveats, the privacy rules, and the part most tutorials still don't cover: how location signals now feed AI search.
1. Pick an IP geolocation API
Don't build this yourself. The IP-to-location databases that power commercial APIs are updated daily from dozens of sources, and a self-rolled lookup will be wrong inside a week. Pick a provider:
Free tier with 1k req/day, JSON response, no signup needed for prototypes.
50k req/month free, paid tiers add ASN, company and carrier data.
The gold standard. Self-host the binary database for offline lookups at scale.
Threat intelligence + geolocation in one call - useful for fraud filters.
2. Detect the city in the browser
The simplest pattern is a single fetch from the browser to a JSON endpoint. The API sees the visitor's IP automatically and returns the city. Drop the result into the DOM and you're done.
// Detect the visitor's city in the browser
async function showCity() {
try {
const res = await fetch("https://ipapi.co/json/");
const { city, region, country_name } = await res.json();
document.querySelector("#hello").textContent =
`Hello, ${city}, ${region}!`;
} catch (err) {
// Always have a fallback - blocks, AdBlockers and offline users
document.querySelector("#hello").textContent = "Hello!";
}
}
showCity();The catch is that ad blockers, VPNs and corporate firewalls will sometimes block third-party API endpoints, so always have a graceful fallback. Never assume the lookup succeeded.
3. Detect the city on the server
For pages where personalisation needs to be in the initial HTML (for example, a hero headline), do the lookup on your server before rendering. Most edge runtimes - Vercel, Cloudflare Workers, Netlify Edge - already expose the visitor's city as a request header, so you don't even need an API call.
// Edge runtime: read the city directly from request headers
export const runtime = "edge";
export default function Page({ headers }) {
const city = headers.get("x-vercel-ip-city") ?? "your city";
return <h1>Hello, {decodeURIComponent(city)}!</h1>;
}Outside an edge runtime, pass the visitor's IP to your chosen provider in a server-side fetch. Cache aggressively - the city for a given IP doesn't change between page loads, so a 1-hour cache cuts API costs by an order of magnitude.
4. Be honest about accuracy
Commercial IP databases are 55-80% accurate at the city level, depending on country and network type. They're much better at country level (95%+), and worse on mobile networks and corporate VPNs. Build for that:
Rules of thumb
- Use it for delight, not gatekeeping. "Hello, London!" is fine. Blocking content based on detected city is not.
- Always offer an override.Let the user pick a different city if you got it wrong - a tiny "not in [city]?" link is enough.
- Never use it for security decisions. VPNs, Tor and mobile carriers make IP geolocation fundamentally unreliable as an identity signal.
5. Handle the privacy side properly
Under the GDPR, the UK Data Protection Act and most other modern privacy laws, an IP address is personal data. You don't need explicit consent for purely operational uses like fraud prevention or language detection, but the moment you store it, profile the user, or pair it with marketing analytics you should disclose the practice in your privacy policy and respect any consent preferences. As always, talk to your legal team for your specific jurisdiction and use case.
One subtle but important rule: don't personalise the page for crawlers. Both Googlebot and the AI crawlers (GPTBot, ClaudeBot, PerplexityBot, Google-Extended) should always see the canonical, non-personalised version. Otherwise you risk poisoning your AI search visibility with city-specific content that doesn't match what real users see.
6. How geolocation feeds GEO and AI search
Geolocation data also plays a growing role in modern Generative Engine Optimization (GEO), helping AI systems personalise results based on location signals. When a user asks ChatGPT for "the best Italian restaurant near me" or Perplexity for "pet-friendly hotels in Amsterdam", the assistant doesn't guess - it weights structured location data (LocalBusiness schema, NAP consistency, city pages, geo-relevant backlinks) and returns the brands with the strongest local entity signals.
Showing the visitor's city in your hero is the client-side surface of this. The deeper play is making sure your brand is the one those AI assistants cite when someone in that city asks for a recommendation - because the brand they cite is the brand that gets the customer.
That's the core of what Geolify builds. Every GEO package tunes the per-platform location signals each AI assistant rewards - across ChatGPT, Claude, Gemini, Perplexity, Grok, Copilot and Google AI Overviews - so when a visitor in your target city asks for the best option in your category, your brand is the one that gets named.
For pure local plays - service businesses, multi-location brands, anything with a postcode - the Local GEO packages are scoped exactly for this. And if you want to understand how each assistant weights location differently, the per-platform playbooks for ranking in ChatGPT, Perplexity and Google AI Overviews break it down by platform.
Recap
IP geolocation is a 30-line feature on the surface and a much deeper conversation underneath. Get the basics right - pick a real provider, handle errors gracefully, don't personalise for crawlers, respect privacy law - and the little "Hello, London" touch will quietly lift conversion across every page it sits on.
The bigger opportunity is what comes after. Location is no longer just a CSS personalisation trick - it's a ranking signal that AI assistants now use to decide which brands to recommend. The brands that invest in their local entity signals today are the brands that AI search will keep citing tomorrow.
Turn location signals into AI citations
Geolify GEO packages get your brand named inside ChatGPT, Claude, Gemini, Perplexity, Grok, Copilot and Google AI Overviews. Keyword scoped, delivered in 14 days, from $499.
FAQ
Is IP geolocation accurate enough to show a visitor's city?
For most consumer ISPs, commercial IP geolocation databases are 55-80% accurate at the city level and 95%+ accurate at the country level. It's perfect for personalisation ('Hello, London!'), localised pricing or showing the nearest store - but it should never be used for anything security-critical, since VPNs, mobile carriers and corporate proxies routinely route traffic through cities the visitor isn't in.
Do I need cookie consent to use IP geolocation?
Under the GDPR and the UK Data Protection Act, an IP address is personal data. You don't need consent for purely operational uses (fraud prevention, language detection, currency formatting), but if you store it, profile the user, or pair it with marketing analytics you should disclose it in your privacy policy and respect cookie/consent preferences. Always defer to your legal team on the specific use case.
Will showing a visitor's city hurt my SEO or AI search visibility?
No - as long as the personalisation happens client-side (after the page has loaded), or server-side based on the visitor's actual IP rather than the crawler's. Both Googlebot and the AI crawlers (GPTBot, ClaudeBot, PerplexityBot, Google-Extended) should always see the canonical, non-personalised version. Geolify's GEO packages explicitly check that bot user-agents bypass any geolocation logic.
How does IP geolocation relate to GEO (Generative Engine Optimization)?
Modern AI assistants increasingly weight location signals when answering 'near me' or city-scoped queries. ChatGPT, Gemini and Perplexity all factor user location into their retrieval pipelines, and they reward sites with strong, structured city-level signals (LocalBusiness schema, city-specific pages, NAP consistency). Showing a visitor's city is one client-side signal - the deeper GEO play is making sure your brand is the one AI assistants cite when someone asks for the best option in their city.
Which IP geolocation API should I use?
For low volume and quick prototypes, free endpoints like ipapi.co or ipinfo.io are fine. For production, pick a paid provider with an SLA and a published accuracy rate - MaxMind GeoIP2, IPinfo, ipdata or DB-IP are all solid. Self-hosted MaxMind databases are the cheapest at scale but require monthly updates to stay accurate.
Can I rank in ChatGPT for city-specific queries?
Yes, and it's one of the highest-ROI GEO plays right now. ChatGPT, Claude and Perplexity routinely answer 'best [thing] in [city]' style queries with named recommendations, and the brands they cite are usually those with strong local entity signals - city pages, LocalBusiness schema, consistent citations across review sites, and geo-relevant backlinks. Geolify's Local GEO packages are scoped exactly for this.