To show a visitor’s approximate country or region in a React app, have your server identify the client IP, look it up with an IP geolocation service or local database, then send only the fields the interface needs to React. Keep provider credentials on the server. Use the browser Geolocation API instead when you need device coordinates and can ask the visitor for permission.
How IP geolocation works in a React app
React runs in the visitor’s browser, so it should request a location result from your own backend rather than call a paid geolocation provider with a secret token. The backend obtains the client IP—often from a correctly configured reverse proxy—looks it up, and returns a small JSON response. For example, an interface that only needs to personalize a greeting may need the country, not the full provider record.
IP geolocation can support coarse localization, routing, or fraud screening. It does not identify a person’s exact location: VPNs, proxies, mobile networks, privacy relays, and provider coverage can all affect the result. MaxMind says its IP geolocation data must not be used to identify a specific household, individual, or street address: MaxMind’s GeoIP data correction guidance.
Illustrative server route
This Express-style example shows the separation between server and browser. The proxy helper is intentionally abstract: implement it for your hosting setup and trust only headers set by infrastructure you control. Confirm the provider’s current endpoint, authentication, response fields, quotas, and proxy guidance before deploying; those details can change.
Free tools Windows power users keep installed
One-click scans. No signup required.
#1 Best Overall
app.get('/api/visitor-location', async (req, res) => {
const ip = getClientIpFromTrustedProxy(req);
const response = await fetch(`https://ipinfo.io/${ip}/json`, {
headers: {
Authorization: `Bearer ${process.env.IPINFO_TOKEN}`
}
});
if (!response.ok) {
return res.status(502).json({ error: 'lookup_unavailable' });
}
const data = await response.json();
res.json({
country: data.country ?? null,
region: data.region ?? null,
city: data.city ?? null
});
});
IPinfo’s Core API documents city, region/state, country, postal code, ASN details, and network indicators such as VPN, proxy, Tor, hosting, anycast, mobile, and satellite: IPinfo Core API documentation. Return only what your app actually uses. A provider API or local GeoIP database will have different setup and operational requirements.
React component with request states
Handle loading, success, and failure explicitly. The component should not assume that every lookup returns a city or even a location.
function VisitorLocation() {
const [state, setState] = React.useState({ status: 'loading' });
React.useEffect(() => {
let active = true;
fetch('/api/visitor-location')
.then(response => {
if (!response.ok) throw new Error('lookup failed');
return response.json();
})
.then(data => {
if (active) setState({ status: 'ready', data });
})
.catch(() => {
if (active) setState({ status: 'error' });
});
return () => { active = false; };
}, []);
if (state.status === 'loading') {
return <p>Finding your approximate region…</p>;
}
if (state.status === 'error') {
return <p>Location unavailable.</p>;
}
const { city, region, country } = state.data;
const label = [city, region, country].filter(Boolean).join(', ');
return <p>{label || 'Region unavailable'}</p>;
}
The cleanup prevents a late response from updating a component that has unmounted. In production, also consider request cancellation, caching, rate limits, timeouts, and an intentional fallback for missing fields.
IP lookup or browser geolocation?
Choose based on the precision and consent the feature actually needs. An IP lookup generally requires a server or local database request and does not prompt the browser for location permission. Browser geolocation can provide device-level coordinates, but the visitor must grant permission and the page must run in a secure context such as HTTPS.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchRank #3
| Consideration | IP geolocation | Browser Geolocation API |
|---|---|---|
| Result | Approximate location inferred from an IP address; precision varies by network and provider. | Device position, potentially more precise; suitability depends on the device and environment. |
| Visitor prompt | No browser location prompt is normally required. | Requires user permission; explain the need and request it in response to a clear user action. |
| Dependency | Backend plus geolocation provider or a maintained local database. | Browser support, secure context, permission, and applicable permissions policy. |
| Typical fit | Coarse region personalization, localization, routing, or screening. | A feature that genuinely needs device coordinates, such as a user-requested nearby result. |
| Common failure | VPN, proxy, carrier network, privacy relay, missing provider data, or provider outage. | Permission denied, insecure page, blocked policy, unavailable position, or device timeout. |
MDN documents the permission prompt and the secure-context requirement for the Geolocation API: MDN: Geolocation API and MDN: getCurrentPosition(). The API offers getCurrentPosition() for a one-time position and watchPosition() for ongoing updates. The W3C specification describes geolocation as a powerful feature requiring express end-user permission and notes privacy risks and permission lifetimes: W3C Geolocation Recommendation.
Security and privacy checks
- Protect the provider credential. Keep tokens and database credentials in server-side environment configuration; never bundle them into React code.
- Trust the right client-IP source. Normalize and validate IP headers according to your known proxy or hosting configuration. Blindly trusting a client-supplied forwarding header can let a visitor choose the address being looked up.
- Limit data. Send and retain only fields the feature needs. Decide how long lookup results and request logs are kept, and document that retention in your privacy practices.
- Use HTTPS. Browser geolocation is restricted to secure contexts. See MDN: Secure contexts.
- Check iframe policy. When geolocation is used in an iframe or cross-origin content, review the
Permissions-Policyheader and the iframe’s permissions. A restrictive policy can block calls and result inPERMISSION_DENIED: MDN: geolocation Permissions-Policy directive. - Explain and ask deliberately. Request device location only when it is needed, explain the benefit before the browser prompt, and provide a way to continue without it.
Handle unavailable location gracefully
Neither approach guarantees a usable result. For IP lookup, a VPN or mobile carrier may map to a different area, the provider may omit city-level data, or the service may be unavailable. For browser geolocation, the visitor may deny permission, the browser may block access, or the device may not return a position. Show a neutral fallback rather than treating missing location as an application error the visitor must resolve.
Rank #4
If the feature depends on a specific area, let the user select it manually. For a nonessential personalization, omit the location-specific content when the lookup fails. Do not infer consent to device tracking from an IP lookup: they are separate mechanisms with different data and privacy implications.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Accuracy, cost, and provider choice
There is no universal accuracy percentage that applies to every IP address, geography, provider, and network type. Compare providers using their current documented geographic coverage, available fields, update practices, rate limits, retention terms, and legal terms. Account for latency and service cost in your own deployment rather than assuming a provider’s lookup is free or instantaneous. For a local database, also plan for updates and a way to handle stale or missing records.
Quick Recap
Best Value
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

