Kamero

How to Get User Location by IP Address in JavaScript

Detecting a visitor's location is one of the most common requirements in web development. Whether you're personalizing content, setting default timezones, or showing localized pricing, IP geolocation gives you an approximate location without asking for browser permissions.

This guide walks through every approach — from a simple fetch call to production-ready React hooks and Next.js server-side patterns.

The Basics: Fetch API

The simplest way to get a user's location by IP is a single fetch call to a geolocation API. No API key, no SDK, no setup:

const response = await fetch("https://geo.kamero.ai/api/geo");
const location = await response.json();

console.log(location.city);      // "San Francisco"
console.log(location.country);   // "US"
console.log(location.timezone);  // "America/Los_Angeles"
console.log(location.latitude);  // "37.7749"
console.log(location.longitude); // "-122.4194"

The API returns 10 data points: ip, city, country, countryRegion, continent, latitude, longitude, timezone, postalCode, and region.

With Error Handling

In production, you should always handle network failures and unexpected responses:

async function getUserLocation() {
  try {
    const res = await fetch("https://geo.kamero.ai/api/geo");
    if (!res.ok) {
      throw new Error(`HTTP ${res.status}`);
    }
    return await res.json();
  } catch (error) {
    console.error("Failed to get location:", error);
    return null;
  }
}

const location = await getUserLocation();
if (location?.city) {
  console.log(`Welcome from ${location.city}, ${location.country}!`);
}

React Hook: useGeolocation

If you're building with React, a custom hook keeps your components clean:

import { useState, useEffect } from "react";

interface GeoData {
  ip: string;
  city: string;
  country: string;
  countryRegion: string;
  continent: string;
  latitude: string;
  longitude: string;
  timezone: string;
  postalCode: string;
  region: string;
}

export function useGeolocation() {
  const [location, setLocation] = useState<GeoData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch("https://geo.kamero.ai/api/geo")
      .then((res) => {
        if (!res.ok) throw new Error("Failed to fetch");
        return res.json();
      })
      .then(setLocation)
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  return { location, loading, error };
}

Then use it in any component:

function WelcomeBanner() {
  const { location, loading } = useGeolocation();

  if (loading) return <p>Loading...</p>;
  if (!location) return null;

  return (
    <p>
      Welcome from {location.city}, {location.country}!
    </p>
  );
}

Next.js: Server-Side Geolocation

In Next.js, you can detect location on the server using Vercel's built-in geolocation headers. This avoids an extra API call entirely:

// app/page.tsx (Server Component)
import { headers } from "next/headers";

export default async function Page() {
  const headerList = await headers();
  const city = headerList.get("x-vercel-ip-city") || "Unknown";
  const country = headerList.get("x-vercel-ip-country") || "Unknown";

  return <h1>Hello from {city}, {country}!</h1>;
}

This only works when deployed to Vercel. For other hosting providers, use the client-side fetch approach or call the Kamero API from a server action.

Practical Example: Auto-Detect Timezone

One of the most useful applications is automatically displaying times in the visitor's timezone:

async function getVisitorTimezone() {
  const res = await fetch("https://geo.kamero.ai/api/geo");
  const { timezone } = await res.json();
  return timezone; // e.g., "America/New_York"
}

// Format a date in the visitor's timezone
const tz = await getVisitorTimezone();
const formatted = new Date().toLocaleString("en-US", {
  timeZone: tz,
  dateStyle: "full",
  timeStyle: "short",
});
console.log(formatted);
// "Monday, February 9, 2026 at 3:45 PM"

Practical Example: Show Localized Content

Redirect or display content based on the visitor's country:

const { country } = await getUserLocation();

const greetings = {
  US: "Hey there! đŸ‡ē🇸",
  GB: "Hello! đŸ‡Ŧ🇧",
  DE: "Hallo! 🇩đŸ‡Ē",
  JP: "こんãĢãĄã¯! đŸ‡¯đŸ‡ĩ",
  IN: "ā¤¨ā¤Žā¤¸āĨā¤¤āĨ‡! đŸ‡ŽđŸ‡ŗ",
};

const greeting = greetings[country] || "Welcome! 🌍";

IP Geolocation vs Browser Geolocation

It's worth understanding the difference between these two approaches:

FeatureIP GeolocationBrowser Geolocation
Permission RequiredNoYes (user prompt)
AccuracyCity-level (~5-25km)Street-level (~10m)
Works Server-SideYesNo
Speed~50ms1-10 seconds
VPN AffectedYesNo
Use CasePersonalization, analyticsMaps, navigation, delivery

For most web applications, IP geolocation is the right choice because it's instant, requires no user interaction, and works on both client and server. Use browser geolocation only when you need precise coordinates (e.g., delivery apps).

Tips for Production

Start Using Kamero Geo API

No API key. No rate limits. Just fetch and go.

Read the Docs →