How to determine a user’s IP address and more with JavaScript and the freegeoip.net API

IP v4 address

Updated: this post has been updated to use freegeoip.app instead of freegeoip.net. freegeoip.net recently changed to ipstack.com and stopped offering a free HTTPS endpoint (although their HTTP endpoint is offered for free).

This guide shows you how to retrieve the user’s IP address and location information using JavaScript and the freegeoip.app API. We assume for the purposes of this guide that usage of the HTML5 Geolocation API is not an option (e.g. you don’t want to interrupt the user experience by asking the user to allow the browser to send location information, your site doesn’t have an SSL certificate, etc.).

The freegeoip.app API

The freegeoip.app API is a free service that limits you to a maximum of 15,000 queries per hour. That should be more than enough for most people’s needs!

The API is free and open source. You can download it and deploy it on your own infrastructure if you wish to control aspects such as:

  • Pointing API calls to your own domain
  • Hosting the API on servers closer to your users
  • Handling more than 15,000 API calls per hour

Licensing: While the freegeoip.net API is free and open source under a 3-clause BSD license, keep in mind that the underlying data is from MaxMind’s free GeoLite2 database. MaxMind provides this under a Creative Commons Attribution-ShareAlike 4.0 International license.

Accuracy: the accuracy of the results is deemed “inherently imprecise”. Most locations are reported near the center of the population group. This means that you can get a general idea of where your user is located, but not be able to pinpoint them to a specific address. If you require more accuracy, and are willing to pay for it, you can consider MaxMind’s GeoIP2 product or similar other offerings.

Retrieving a user’s IP address and location info

Let’s look at some JavaScript code to retrieve and display IP and location information.

JavaScript helper library

First, let’s create a helper library to handle calls to the freegeoip.app API.

You can view the full source code for the library here. Let’s walk through the code.

First, load jQuery if it hasn’t already been done so

//Load jQuery if it hasn't been already loaded
if (window.jQuery === undefined) {
var s = document.createElement('script');
s.src = "https://code.jquery.com/jquery-3.2.1.min.js";
document.head.appendChild(s);
}

Next, declare a namespace to ensure our code doesn’t conflict with any other libraries. At the same time declare a variable to store any lookup data.

var ipLookup = {};
ipLookup.data = {};

Then, we have a function to conduct the lookup and return the data in JSON format. Promises are used here so that the lookup can run asynchronously and inform the calling code when the API’s response is ready.

/**
* Executes an IP data lookup for current client
* @returns {Promise}
*/
ipLookup.lookup = function () {
return new Promise(function(resolve,reject) {
//If no arguments are provided, the API looks up details for the IP of
// originating request.
$.getJSON('https://freegeoip.app/json/').done(function(data) {
ipLookup.data = data;
resolve(data);
}).fail(function(data) {
reject(data);
});
});
};

Conducting IP lookups using JavaScript

Now that we have the helper library, let’s look at how we use it in our frontend code.

Let’s step through the relevant code. First, load the helper library that was created above.

<script src="ip-lookup.js"></script>

Next, make a call to ipLookup.lookup() at the point where you require the IP address and related information. Since the function returns a Promise, you can use .then() to dictate what happens after the freegeoip.app API returns a response. In this example the outputIpDetails() function is triggered.

ipLookup.lookup().then(function(data) {
outputIpDetails();
});

Now, let’s do something with the data. In this case we’re simply iterating through the values stored in the ipLookup.data object and outputting it to a table.

function outputIpDetails() {
var ipDetails = ipLookup.data;

Object.keys(ipDetails).forEach(function(key) {
var val = ipDetails[key];
$('#output-' + key).html(val);
});
}

Respect your users’ privacy

While this guide outlines how straightforward it is to retrieve IP and location information for a user on your site, make sure that the information is used in such a way that doesn’t violate your users’ privacy. This generally means:

  • Update your site’s terms and services to indicate that you are retrieving IP and location information.
  • Do not store IP addresses or postcode information unless absolutely necessary.
  • Only retrieve IP and location information when you need it (i.e. don’t retrieve the information by default for all users if you only need the information for a subset of your users).
Did you find this helpful and think it would be beneficial for someone else? Share now!

2 thoughts on “How to determine a user’s IP address and more with JavaScript and the freegeoip.net API

    • Vinoaj Vijeyakumaar Post authorReply

      Hi – thanks for bringing that to my attention. The API endpoint had changed. I’ve modified my writeup and code to use another freely available API

Leave a Reply

Your email address will not be published. Required fields are marked *