Notes

Three ways of determining the user's country inside the browser (Geolocation API, IP address, Timezone)

Edit on GitHub


Web Development
2 minutes

For Node based apps you can use countries-and-timezones which is ~9kb and can give you a country based on the timezone

Geolocation API

This i didn’t pay much attention to because i did not want to prompt the user to get their permission for using their location. Overtly creepy.

IP Address

Services like ipinfo.io give you 50k requests/month for free.

1fetch('https://extreme-ip-lookup.com/json/')
2  .then((res) => res.json())
3  .then((response) => {
4    console.log('Country: ', response.country)
5  })
6  .catch((data, status) => {
7    console.log('Request failed')
8  })
 1{
 2  "businessName": "Digitalcourage.de",
 3  "businessWebsite": "www.digitalcourage.de",
 4  "city": "Amsterdam",
 5  "continent": "Europe",
 6  "country": "Netherlands",
 7  "countryCode": "NL",
 8  "ipName": "tor-exit-relay-7.anonymizing-proxy.digitalcourage.de",
 9  "ipType": "Business",
10  "isp": "Cia Triad Security LLC",
11  "lat": "52.37403",
12  "lon": "4.88969",
13  "org": "Zwiebelfreunde E.V.",
14  "query": "185.220.102.253",
15  "region": "Noord-Holland",
16  "status": "success"
17}

Timezone (Internationalization API)

1console.log(Intl.DateTimeFormat().resolvedOptions().timeZone) // 'Asia/Karachi'

I ended up using countries-and-timezones which is a lightweight JS lib for matching a timezone with a country. Got what i wanted in less than 20kb and no external API calls.

Keep in mind that this relies on the user setting their timezone correctly. While one timezone can be in multiple countries (for example: Europe/Zurich is in Germany, Switzerland and Liechtenstein..), there are actually separate timezone definitions for each country (for example Europe/Berlin and Europe/Vaduz), that the user has probably set correctly. But there’s definitely no guarantee.

(Since my use case was pre-selecting a country in a country selection dropdown, i have provided them with a simple way of correcting any mismatches. The detection and pre-selection is just to make the user’s life easy)

1<script src="https://cdn.jsdelivr.net/gh/manuelmhtr/countries-and-timezones@latest/dist/index.min.js"></script>
1// Load the file if you have saved it locally and not sourcing a script in HTML
2// import "../lib/countries-and-timezones.min.js"
3
4let browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone
5let browserCountry = ct.getCountryForTimezone(browserTimezone) // {id: "PK", name: "Pakistan", timezones: Array(1)}