You can use my service, http://ipinfo.io, for this. It will give you the client IP, hostname, geolocation information (city, region, country, area code, zip code etc) and network owner. Here's a simple example that logs the city and country:

Copy$.get("https://ipinfo.io", function(response) {
    console.log(response.city, response.country);
}, "jsonp");

Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/

The location will generally be less accurate than the native geolocation details, but it doesn't require any user permission.

Answer from Ben Dowling on Stack Overflow
🌐
Stack Exchange
softwarerecs.stackexchange.com › questions › 87717 › how-to-get-country-from-javascript-geolocation-api-or-similar-on-a-web-page
web development - How to get country from Javascript Geolocation API or similar on a web page? - Software Recommendations Stack Exchange
August 17, 2023 - I am trying to get precise location to country with a web page. I know there is geolocation using Javascript but that is latitude and longitude. I am trying for any way on a web page to get as prec...
🌐
TecHighness
techighness.com › home › get user country and region on browser with java script only
Get User Country and Region on Browser With JavaScript Only - TecHighness
December 26, 2022 - If you’re not interested in the internal working and implementation, use getCountriesForTimezone method of the npm package countries-and-timezones. Simply get the user timezone from step 1 below and pass it to getCountriesForTimezone(timezone) to get user country name and iso2 code (id).
🌐
GitHub
gist.github.com › remy727 › 968e466a6c61bf636f54aeb91650b28e
Get Country name from Country code using JavaScript · GitHub
Get Country name from Country code using JavaScript - get-country-name-from-country-code.js
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-get-country-name-from-country-code
Get Country name from Country code in JavaScript | bobbyhadz
Use the `Intl.DisplayNames()` constructor to get a country name from a country code in JavaScript.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › Locale › region
Intl.Locale.prototype.region - JavaScript - MDN Web Docs
July 22, 2025 - The region accessor property of Intl.Locale instances returns the region of the world (usually a country) associated with this locale.
🌐
Laracasts
laracasts.com › discuss › channels › javascript › javascript-how-to-get-country-code-from-country-name
Javascript how to get Country code from country name?
@boyjarv I am actually having a hard time finding a way to do this from the browser There is this plugin https://www.npmjs.com/package/country-code-lookup however that requires getting a plugin ... fetch("https://restcountries.eu/rest/v2/name/kenya").then(resp=>{ console.log('resp: ',resp); return resp.json(); }).then(json=>{ console.log('Kenya: ',json[0].alpha2Code); }) Can't get anything logged out?!
Find elsewhere
🌐
DB-IP
db-ip.com › tutorials › javascript-get-visitor-country
Get visitor country with Javascript
DB-IP demonstrates how to get a website visitor's country based on their IP address with client side JavaScript code. Familiarize yourself with ways for performing several tasks with our other tutorials and code samples.
🌐
YouTube
youtube.com › watch
Get Country Information in JavaScript - YouTube
How to get country information in JavaScript? In this tutorial we are going to populate country list. Then on selecting a country, detailed country informati...
Published   November 23, 2023
🌐
DEV Community
dev.to › muzudre › how-to-get-visitors-location-ie-country-using-geolocation-in-javascript-2595
How to get visitor's location (country) using geolocation in JavaScript? - DEV Community
September 22, 2022 - #javascript #beginners #webdev · I wanted to localize client side pricing for few countries without using any external API, so I used local Date object to fetch the country using new Date()).toString().split('(')[1].split(" ")[0] document.write((new Date()).toString().split('(')[1].split(" ")[0]) Basically this small code snippet extracts the first word from the Date object.
🌐
npm
npmjs.com › package › geoip-country
geoip-country - npm
3 weeks ago - A native nodejs API to get country information from ip address.
      » npm install geoip-country
    
Published   May 27, 2026
Version   5.0.202605270000
🌐
DEV Community
dev.to › idrisakintobi › how-to-retrieve-user-country-from-ip-address-4i9b
How to Retrieve User Country from IP Address - DEV Community
March 26, 2025 - import { readFileSync } from "fs"; import { Reader } from "maxmind"; // Synchronous database opening const dbBuffer = readFileSync("geolite2-city-ipv4.mmdb"); // This reader object should be reused across lookups as creation of it is expensive. const reader = new Reader(dbBuffer); const ipAddr = "154.113.170.145"; const IP2City = (ip) => { try { const { city, country_code } = reader.get(ip); return { city, countryCode: country_code }; } catch (error) { console.log(error); // Handle the error as needed.
🌐
GitHub
github.com › hannesgassert › countrynames
GitHub - hannesgassert/countrynames: ISO 3166 Country Name / Code Mapper in Javascript · GitHub
// Returns 'CH' countrynames.getCode('Switzerland') // Returns 'BB' countrynames.getCode('BarbaDOS')
Starred by 42 users
Forked by 15 users
Languages   JavaScript
Top answer
1 of 3
39

Using jQuery, this line will display your user's country code.

  $.getJSON('https://freegeoip.net/json/', function(result) {
    alert(result.country_code);
  });
2 of 3
32

navigator.language isn't reliable as one of your linked questions states.

The reason this is asked a lot, but you're still searching says something about the problem. That language detection purely on the client side is not anything close to reliable.

First of all language preferences should only be used to detect language preferences - i.e. not location. My browser is set to en_US, because I wanted the English version. But I'm in the UK, so would have to alter this to en_GB to have my country detected via my browser settings. As the 'customer' that's not my problem. That's fine for language, but no good if all the prices on your site are in $USD.

To detect language you really do need access to a server side script. If you're not a back end dev and want to do as much as possible on the client side (as your question), all you need is a one line PHP script that echos back the Accept-Language header. At its simplest it could just be:

<?php
echo $_SERVER['HTTP_ACCEPT_LANGUAGE']; 
// e.g. "en-US,en;q=0.8"

You could get this via Ajax and parse the text response client side, e.g (using jQuery):

$.ajax( { url: 'script.php', success: function(raw){
    var prefs = raw.split(',');
    // process language codes ....
} } );

If you were able to generate your HTML via a back end, you could avoid using Ajax completely by simply printing the language preferences into your page, e.g.

<script>
    var prefs = <?php echo json_encode($_SERVER['HTTP_ACCEPT_LANGUAGE'])?>;
</script>

If you had no access to the server but could get a script onto another server, a simple JSONP service would look like:

<?php
$prefs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$jsonp = 'myCallback('.json_encode($prefs).')';

header('Content-Type: application/json; charset=UTF-8', true );
header('Content-Length: '.strlen($jsonp), true );
echo $jsonp;

Using jQuery for your Ajax you'd do something like:

function myCallback( raw ){
    var prefs = raw.split(',');
    // process language codes ....
}
$.ajax( {
    url: 'http://some.domain/script.php',
    dataType: 'jsonp'
} );

Country detection is another matter. On the client side there is navigator.geolocation, but it will most likely prompt your user for permission, so no good for a seamless user experience.

To do invisibly, you're limited to geo IP detection. By the same token as above, don't use language to imply country either.

To do country detection on the client side, you'll also need a back end service in order to get the client IP address and access a database of IP/location mappings. Maxmind's GeoIP2 JavaScript client appears to wrap this all up in a client-side bundle for you, so you won't need your own server (although I'm sure it will use a remote jsonp service). There's also freegeoip.net, which is probably less hassle than MaxMind in terms of signing up, and it appears to be open source too.

Top answer
1 of 3
55

Another option could be using the (internationalization API)

console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)
2 of 3
52

There are multiple options to determine the locale. In descending order of usefulness, these are:

  1. Look up the IP address, with an IP geolocation service like Maxmind GeoIP. This is the location the request is coming from, i.e. if an American vacations in Italy and uses a Swedish VPN, it will return Sweden.

It can only be done with the help of the server. The main advantage is that it's very reliable. The accuracy will be country or region for free services, city or region for paid ones.

  1. Look up the precise location on Earth from the browser with the geolocation API. An American vacationing in Italy using a Swedish VPN will register as Italy.

The answer will be very precise, usually no more than 10m off. In principle, it could work client-side, although you may want to perform the coordinate -> country lookup on the server. The main disadvantages are that not all devices have either GPS or WiFi position, and that it generally requires explicit user consent.

  1. Look in the Accept-Language header on the server (or with the help of the server), and extract the locale information. An American vacationing in Italy using a Swedish VPN will register as USA.

The downside is that this is a setting that's extremely easy to change. For instance, English speakers around the world may prefer en-US settings in order to avoid machine-translated text. On modern browsers (as of writing not IE/Edge, and only Safari 11+), you can also request navigator.languages.

  1. navigator.language is the first element of the navigator.languages header. All of the considerations of navigator.languages apply. On top, this information can sometimes be just the language without any locale (i.e. en instead of en-US).

  2. Use another, third-party service. For instance, if the user signs in via a Single-Sign-On system such Facebook connect, you can request the hometown of the user. This information is typically very unreliable, and requires a third party.

🌐
Medium
walidov.medium.com › super-simple-way-to-get-visitors-country-using-jquery-and-myip-com-706c813b44a7
Super simple way to get visitors Country using jQuery and MYIP.com - Waleed Asender - Medium
November 10, 2020 - <script> $.get(“https://api.myip.com/", function (data) { // There are 3 values only returned handle them as needed console.log(data.ip); // Visitors IP Address console.log(data.country); // Country Name in English console.log(data.cc); // Country Code }, “json”); </script>
🌐
GitHub
github.com › ishithemes › getvisitorscountry
GitHub - ishithemes/getvisitorscountry: Get Country Code of a Visitor on your Website.
This is a simple JavaScript code that helps you get the country of the visitor on your website and use it to block or redirect visitors based on your requirement.
Author   ishithemes