Watch-IP

Request visitor location from browser JavaScript

This guide adds a complete GET /v1/geo call to a web page: a loading state, a successful result, and a fallback for when the request fails or a field is missing.

Before you start

  • A Watch-IP account and a publishable visitor API key.
  • The key's allowed origins configured to include the page you're testing from.
  • A page served over HTTP(S) — file:// origins can't be added to an allow-list.

1. Call the endpoint

Send the request with your publishable key in the X-Api-Key header. Because the key is designed to be publishable, seeing it in the browser network tab is expected — the allow-listed origin is what limits its use, not secrecy.

JavaScript

async function loadVisitorLocation() {
  const response = await fetch('https://api.watch-ip.com/v1/geo', {
    headers: { 'X-Api-Key': 'YOUR_PUBLISHABLE_KEY' },
  });

  if (!response.ok) {
    throw new Error(`Visitor geolocation failed (${response.status})`);
  }

  return response.json();
}

2. Render a loading state, then the result

Keep your default UI visible until the request resolves, and treat every field as possibly null. Country, city, and timezone are the fields most integrations start with.

JavaScript

const statusEl = document.querySelector('#location-status');
statusEl.textContent = 'Detecting your region…';

try {
  const geo = await loadVisitorLocation();
  statusEl.textContent = geo.city && geo.country
    ? `Showing content for ${geo.city}, ${geo.country}`
    : 'Using the default region';
} catch {
  statusEl.textContent = 'Using the default region';
}

3. Preserve an explicit visitor choice

Check for a stored preference before applying the suggested country or currency, and only fall back to the API result when no preference exists yet.

JavaScript

const preferred = localStorage.getItem('preferredCountry');
const country = preferred ?? geo.country ?? 'US';

Errors and edge cases

A disallowed origin fails the browser's CORS check before your code sees a response — this typically surfaces as a generic network error, not a readable JSON body, so check the allowed-origins configuration first when a request fails silently. A missing field is not an error: treat a null country, city, or timezone value as 'unavailable', not as a bug.

Next step

Once the basic request works, decide how your application should react to the result — see the visitor geolocation product page for the localization pattern, and the reference page for every field the response can contain.

Related pages