This page looks best with JavaScript enabled

Find user's country without Geolocation and IP Lookup

 ·   ·  ☕ 2 min read

I have this nagging problem of determining an end user’s country/region in my web apps. The reasons for doing that are many -

  1. Automatic conversion of an event date/time
  2. Display regional news
  3. Show prices in user’s currency
  4. .. and so on

We could do two things to determine a user’s region -

  1. Use geo location
  2. Use external services to look up the IP

Option (1) is ideal. It is quite easy - thanks to HTML5.

1
2
3
4
5
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(showPosition);
} else {
  x.innerHTML = "Geolocation not supported!";
}

We can use geo location almost always, except that the user gets prompted to allow our app to access her location. This leads to a bad user experience, and more than that, I don’t want the user to think about our app as yet another shady site that collects unneeded personal information.

We avoid the above problem by looking up user IP against a database, which is the second option outlined above. For e.g. you can use APIs from IP Stack, Apility Geo IP lookup, Labstack IP lookup or use the data sets from ip2location to lookup the user region based on IP address.

While not always accurate, looking up the region using IP is a good enough approximation that just works. However, this costs money in form of external services (monthly costs) or in form of enhancements in your product + cost of third party datasets.

A third option exists if you are not a super professional org and can live with “approximated” regions - looking up the region using time zone.

Just do this in Javascript ..

1
const tzone = Intl.DateTimeFormat().resolvedOptions().timeZone;

tzone gives you the user’s time zone, which can be now looked up to find the country of user.

For e.g. to find whether my user is logging in from India -

1
2
3
4
5
6
function indiaOrBust() {
  const tzone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  return tzone.includes("Kolkata") || tzone.includes("Calcutta")
    ? "India"
    : "Not India";
}

Not really ideal if -

  • you are lucky enough to be in a region with multiple timezones and want to drilldown to the hyper locale.
  • have to distinguish / identify all the countries of the world
  • your “do or die” business logic relies on the country and you may lose a million dollars if that does not work

.. but, it’s a totally workable solution that does not add to the bundle or monetary costs.

See documentation for more details, use Intl and rejoice!

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things