IPinfo - Comprehensive IP address data, IP geolocation API and database My IP ↗or
7 days ago by Meghan Prichard 7 min read

Getting Started with Geolocation API in JavaScript

Best JavaScript IP Geolocation API: How to Locate Users in JS

A geolocation API is an essential tool for building modern, personalized, and secure web experiences. It allows developers to determine a user’s approximate physical location and use that data to enhance functionality, like displaying local content, enforcing access restrictions, or detecting fraud. 

Web developers typically rely on two approaches to geolocation: browser-based and IP-based. While browser-based geolocation requires user permission, IP-based geolocation is seamless, accurate, and fast.

IPinfo’s geolocation API provides rich IP data, including city, country, zip code, geographic coordinates, and even IP privacy detection, making it ideal for a myriad of use cases. In this post, we’ll explore how web developers can use IPinfo’s API to power location-aware features while improving security and user experience.

Understanding Geolocation APIs

Geolocation APIs allow developers to determine where users are connecting from — but not all IP data is created equal. While many providers rely solely on third party data from WHOIS records or geofeeds, IPinfo takes a radically different approach to accuracy. We aggregate IP data from our Probe Network, a distributed network of 1,000 servers across 130 countries. Our proprietary models pinpoint location using a GPS-like triangulation method from our worldwide servers.

We also actively verify data through 400 billion real-time IP measurements per week, far beyond what passive sources provide. This ensures our IP data reflects real-world conditions, making IPinfo the go-to API for developers who need precise, trustworthy geolocation. Read more about the best IP geolocation API.

Key use cases for geolocation APIs like ours include:

  • Targeted advertising: Deliver location-specific ads for better engagement and ROI
  • Fraud detection: Flag suspicious behavior based on geographic anomalies
  • Regulatory compliance: Enforce content restrictions or data policies by region
  • Real-time inventory updates: Show product availability based on a user’s location
  • Cybersecurity: Block traffic from high-risk countries or detect anonymizing services

Best-in-Class IP Data Available Now

Start using IPinfo’s IP Geolocation API today

Sign up for free

Retrieving an IP Address Location Using JavaScript

Web developers can access geolocation data using two main methods: the browser’s navigator.geolocation API, which relies on GPS or WiFi (with user consent) location (with user consent). IP-based geolocation via IPinfo’s API requires no permission and delivers reliable location data based on the user’s IP address.

Get IP geolocation in C sharp

Checking Browser Geolocation Support

Browser-based geolocation requires user permission and works only over HTTPS. You can check for support like this:

  if ("geolocation" in navigator) {
  console.log("Geolocation is supported.");
} else {
  console.log("Geolocation is not supported.");
}

Using the Browser’s Geolocation API

The navigator.geolocation.getCurrentPosition() method allows developers to retrieve the user's current geographic location. It prompts the user for permission, then returns the latitude and longitude via a callback function. This method works best on mobile devices or when WiFi is enabled, as it uses GPS, cell towers, or WiFi data for accuracy.

Here's a simple example:

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
      const lat = position.coords.latitude;
      const lon = position.coords.longitude;
      console.log(`Latitude: ${lat}, Longitude: ${lon}`);
    });
  } else {
    console.log("Geolocation is not supported by this browser.");
  }
}

The Limitations of Browser-Based Geolocation

Browser-based geolocation comes with several challenges. First, it requires explicit user permission, triggering pop-up requests that users may deny, blocking location access entirely. Second, for security reasons, most browsers restrict geolocation features to HTTPS sites, limiting use on unsecured HTTP pages. Third, the accuracy of browser geolocation can vary widely depending on the device and environment. On mobile devices, GPS provides precise data, but on desktops, the location is often estimated using WiFi networks, which can be less accurate than GPS based geolocation.

These limitations make browser-based geolocation less consistent and sometimes unsuitable for applications demanding high-accuracy location data.

Retrieving Geolocation via IPinfo’s API

IPinfo’s IP Geolocation API offers a powerful alternative to browser-based geolocation by providing accurate location data based on the user’s IP address. Unlike browser geolocation, which requires explicit user permission and works only on HTTPS sites, IPinfo’s API operates seamlessly without any consent pop-ups or security restrictions. This makes it ideal for applications needing quick, reliable location insights without interrupting user experience. 

Leveraging active network measurements, multiple data sources, and proprietary algorithms, IPinfo ensures high accuracy and near real-time data. Additionally, the API can detect VPNs, proxies, and other IP anonymizing services, enhancing security and fraud detection capabilities. Because using IP geolocation data relies on IP-based data rather than device hardware features, it works consistently across all internet connected devices, and can be used both client-side and server-side. This combination of accuracy, ease of use, and permission-free operation makes IPinfo’s API a preferred choice for developers seeking dependable geolocation solutions.

Step 1: Get Your Free API Key

Signing up for an IPinfo API key is quick and easy. Simply visit the IPinfo website, create a free account by providing basic details, and receive your API key instantly. This key allows you to access powerful IP geolocation data and start integrating it into your applications right away.

Step 2: Make an API Call in JavaScript

To retrieve IP-based geolocation data using IPinfo’s API, you can use a simple fetch request in JavaScript. This allows you to access details like country, ASN, and more using the user’s IP address. Here's a basic example:

function fetchIPInfo() {
  fetch("https://ipinfo.io/json?token=YOUR_API_TOKEN")
    .then(response => response.json())
    .then(data => {
      const parts = data.org.split(' ');
      asn = parts[0];
      orgName = parts.slice(1).join(' ');

      console.log("IP Information:");
      console.log(`IP Address: ${data.ip}`);
      console.log(`City: ${data.city}`);
      console.log(`Region: ${data.region}`);
      console.log(`Country: ${data.country}`);
      console.log(`Location: ${data.loc}`);
      console.log(`Postal Code: ${data.postal}`);
      console.log(`Timezone: ${data.timezone}`);
      console.log(`ASN: ${asn}`);
      console.log(`Organization: ${orgName}`);
    })
    .catch(error => {
      console.error("Error fetching IP data:", error);
    });
}

Step 3: Extracting Geolocation Data

When you call IPinfo’s API, the response includes key geolocation and network data fields. These typically include ip (the IP address), country for geographic location (city-level data is available with our paid products — explore IP data geolocation pricing), ASN and that Autonomous System’s name and domain, and additional fields like privacy for privacy detection (also available on paid plans). This information helps personalize content, enhance security, and detect fraud.

Here’s a sample response from IPinfo Core:

{
  "ip": "149.54.14.128",
  "city": "Kabul",
  "region": "Kabul",
  "country": "AF",
  "loc": "34.5281,69.1723",
  "timezone": "Asia/Kabul",
  "asn": {
    "asn": "AS55330",
    "name": "AFGHANTELECOM GOVERNMENT COMMUNICATION NETWORK",
    "domain": "afghantelecom.af",
    "route": "149.54.14.0/24",
    "type": "government"
  },
  "is_anycast": false,
  "is_mobile": true,
  "is_anonymous": false,
  "is_satellite": false,
  "is_hosting": false
}

These fields are easy to parse and use in your application logic.

Step 4: Displaying Geolocation Data in a Web App

Using IPinfo’s geolocation data, you can customize web content based on a user’s location. For example, you might display local currency, show nearby services, or adjust language settings. Here’s a simple implementation:

fetch("https://ipinfo.io/json?token=YOUR_API_TOKEN")
  .then(response => response.json())
  .then(data => {
    const locationMessage = `Welcome from ${data.city}, ${data.region}, ${data.country}!`;
    document.getElementById("location-banner").innerText = locationMessage;
    
    if (data.country === "FR") {
      // Switch site language or pricing for France
      switchToFrenchContent();
    }
  });

This approach lets you create dynamic, location-aware experiences without user input, improving engagement and relevance automatically.

Comparing IPinfo’s API to Browser-Based Geolocation

When deciding between browser-based geolocation and IP-based geolocation, there are several considerations. Browser geolocation uses GPS, WiFi, or mobile networks to determine location and can be very accurate, especially on mobile devices, but it requires user consent and only works over HTTPS. It’s also limited to frontend environments. 

In contrast, IPinfo’s IP-based geolocation API offers consistent, permission-free access to accurate IP location data, with the added benefit of working on both frontend and backend systems. It also includes advanced features like VPN and proxy detection, which browser geolocation doesn’t provide. For developers who need reliable, scalable, and privacy-aware solutions, IPinfo’s API is the better fit.

Feature

IPinfo API

Browser Geolocation

Accuracy

High

High

Works Without User Permission

Detects VPN/Proxy

Usability in the Backend Services

Advanced JavaScript Use Cases for IP Geolocation

Here are some benefits of IP geolocation for businesses and developers.

Personalizing Website Content

IP geolocation empowers companies to personalize website content by tailoring the experience to a user’s location. Localize product pricing by country, display region-specific promotions, or adjust language and currency settings. This creates a more relevant, engaging experience that boosts user satisfaction and increases conversion rates.

Implementing Location-Based Access Control

Companies can use location-based access control to restrict who sees their digital content based on their country, region, or city. This helps enforce licensing rules, comply with local laws, or block risky traffic. By tailoring access, protect your content and ensure you meet geographic compliance requirements easily.

Enhancing Security with IPinfo’s API

Companies can use IPinfo’s API to detect VPN usage, block suspicious logins, and prevent fraudulent activities. By identifying anonymizing services and high-risk traffic, you can protect your networks, safeguard customer accounts, and reduce fraud losses, strengthening your overall security posture with reliable IP intelligence.

Final Thoughts on JavaScript IP Geolocation APIs

Using an IP geolocation API with JavaScript is a powerful mechanism for creating personalized, secure, and context-aware web experiences. While browser-based geolocation requires user permission and can be inconsistent, IPinfo’s API provides accurate, permission-free IP-based location data that works seamlessly across platforms. Its ease of use, combined with its peerless accuracy and critical features like privacy detection, makes it ideal for enhancing security, preventing fraud, and tailoring content to users’ locations. 

Developers can quickly integrate IPinfo’s API with simple JavaScript fetch calls, accessing detailed, reliable data without interrupting user experience. For companies seeking precision, scalability, and stronger security in their applications, IPinfo’s API delivers both the depth of information and ease of implementation needed for modern web development.

Unlock Accurate IP Geolocation for Your Apps

Experience seamless, accurate location data with IPinfo’s powerful API.

Get started for free

About the author

Meghan Prichard

Meghan Prichard

Meghan is the content strategist at IPinfo, where she develops and writes content for users to better understand the value of IP data and IPinfo products.