No history yet

Third-Party API Fetches

Using External APIs to Find an IP

A web browser, for security reasons, doesn't have a direct way to ask the operating system for its public IP address. JavaScript running on a webpage is sandboxed; it can't just access network-level details. So, how do we find it? We have to ask someone else—an external server.

The logic is simple: when your browser makes a request to a server on the internet, the server sees your public IP address as the origin of that request. If you control the server, you can program it to report that IP address back. But an easier way is to use a third-party service that does exactly this. These services have a single job: you make a request to them, and they respond with the IP address they saw.

A Simple IP Lookup with ipify

One of the most straightforward services is ipify It's free, fast, and requires no authentication. You just need to make a request to their API endpoint. To do this from the browser, we'll use the modern Fetch API which is built into all major browsers for making network requests.

// Function to get the public IP address using ipify
async function getMyIp() {
  try {
    // Make a request to the ipify API
    const response = await fetch('https://api.ipify.org?format=json');

    // Check if the request was successful
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // Parse the JSON response
    const data = await response.json();

    // Log the IP address
    console.log('My public IP is:', data.ip);
    return data.ip;
  } catch (error) {
    console.error('Could not fetch the IP address:', error);
  }
}

// Call the function
getMyIp();

Let's break down the code. We define an async function because fetch is asynchronous; it returns a Promise that resolves with the server's response. We use await to pause the function until the promise is settled. The ?format=json query parameter tells ipify to send the data back as a JSON object, which is easy to work with in JavaScript. The response looks like this: {"ip":"192.0.2.1"}. We then call .json() on the response object, which is another asynchronous step, to parse the response body as JSON. Finally, we can access the IP address with data.ip.

Error handling is crucial. The try...catch block ensures that if the network request fails for any reason (like being offline), our application won't crash. We also check response.ok to handle cases where the server returns an error status code like 404 or 500.

Getting Geolocation Data

Knowing the IP is good, but sometimes you need more context, like the user's city or country. For that, we can use a more advanced service like Abstract API. It provides detailed geolocation data from an IP address. While it has paid tiers, it also offers a generous free plan that's perfect for many applications. You'll need to sign up for a free API key first.

// Replace 'YOUR_API_KEY' with your actual key from Abstract API
const API_KEY = 'YOUR_API_KEY';

async function getGeoData() {
  try {
    const response = await fetch(`https://ipgeolocation.abstractapi.com/v1/?api_key=${API_KEY}`);
    if (!response.ok) {
      throw new Error(`API request failed: ${response.status}`);
    }
    const data = await response.json();

    console.log('Geolocation Data:', data);
    console.log(`You are in ${data.city}, ${data.country}.`);
    return data;

  } catch (error) {
    console.error('Could not fetch geolocation data:', error);
  }
}

getGeoData();

The structure is nearly identical to the ipify example. The key differences are the URL and the addition of the api_key query parameter. The JSON response from Abstract API is much richer, containing fields like city, country, continent, timezone, and information about the internet service provider (ISP).

Common Hurdles

When you make requests from a web page to a domain different from your own, you're making a cross-origin request. Browsers enforce a security policy called (Cross-Origin Resource Sharing) to manage these. If a server doesn't explicitly permit requests from your domain, the browser will block them. Luckily, public APIs like ipify and Abstract API are configured to allow requests from any origin, so you don't have to worry about it in this case. However, if you tried to fetch data from a random website's API, you would likely run into a CORS error.

Another common issue is hitting rate limits. Free APIs can't offer unlimited requests. Abstract API, for instance, allows a certain number of requests per month on its free plan. If you exceed this limit, the API will start returning error responses (often with a 429 Too Many Requests status code). Always check the documentation for the service you're using to understand its limits and handle potential errors gracefully in your code.

Quiz Questions 1/4

Why can't JavaScript running in a web browser directly ask the operating system for the user's public IP address?

Quiz Questions 2/4

When using the Fetch API to get an IP address from a third-party service, the response must be processed with the .json() method. This is because the initial fetch call resolves to...

Using these third-party services is a reliable and standard way to determine a user's public IP address and related information directly in the browser.