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
🌐
Laracasts
laracasts.com › discuss › channels › javascript › javascript-how-to-get-country-code-from-country-name
Javascript how to get Country code from country name?
let found = countryListAllIsoData.find(country => country.name === races.Circuit.Location.country); let code = found ?
🌐
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 - To see how and where you can use it, check track user activity with custom script and restrict content for users of specific countries with JavaScript only. If you’re not interested in the intermediate steps and want the final exact code, head to section 4 at the bottom! 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).
People also ask

How can I get a user's location with JavaScript?
To get a user's location using JavaScript, you can use the built-in 'navigator.geolocation' object, which provides access to the device's location. Another way is to call IP Geolocation API which returns the user's location with accuracy up to the city level.
🌐
geoapify.com
geoapify.com › how-to-get-user-location-with-javascript
How to Get User Location with JavaScript | Geoapify
What is the difference between navigator.geolocation and IP geolocation?
The main difference between 'navigator.geolocation' and IP geolocation is the way they determine the user's location. The 'navigator.geolocation' relies on the GPS receiver of the device, which provides accurate real-time location data. On the other hand, IP geolocation uses the user's IP address to estimate their location, which is usually accurate only at the city or region level. Additionally, 'navigator.geolocation' requires the user's explicit consent to share their location, while IP geolocation does not.
🌐
geoapify.com
geoapify.com › how-to-get-user-location-with-javascript
How to Get User Location with JavaScript | Geoapify
How accurate is IP geolocation compared to GPS-level accuracy provided by 'navigator.geolocation'?
IP geolocation is less accurate than GPS-level accuracy provided by 'navigator.geolocation'. IP geolocation is typically precise up to the city level, whereas 'navigator.geolocation' can provide location data with sub-meter accuracy. However, it's important to note that the accuracy of 'navigator.geolocation' can be affected by factors such as weather conditions, tall buildings, and other obstructions that can interfere with GPS signals.
🌐
geoapify.com
geoapify.com › how-to-get-user-location-with-javascript
How to Get User Location with JavaScript | Geoapify
🌐
Stack Overflow
stackoverflow.com › questions › 68187879 › get-a-country-code-from-navigator-languages-in-a-browser
javascript - Get a country code from 'navigator.languages' in a browser - Stack Overflow
You can try to derive it from IP with geocoding but it's not super reliable. If the user will give you permission you can use html5 geolocation API developer.mozilla.org/en-US/docs/Web/API/Geolocation_API ... @Matt For the most part that may work. But in some cases the geolocation is not necessarily the same as the users' browser language country code. ... What navigator.language, as specified in BCP 47, gets you is the International Standards Organization's ISO 639-1 language code, which is primarily a 2-letter code.
🌐
WeWeb Community
community.weweb.io › ask us anything › how do i?
How do I find someone's country code by their browser? - How do I? - WeWeb Community
August 19, 2023 - How do I find the country that someone belongs to from their browser? I am able to find the time zone via the date extension, but what about the country? For example, I want it to return such that if example someone is from Singapore, it’s “SG”. If someone is from USA, return “US”. ...
🌐
Stack Overflow
stackoverflow.com › questions › 47456836 › how-to-get-country-code-from-browser-url-and-inject-it-in-all-page-links › 47474207
jquery - How to get country code from browser url and inject it in all page links - Stack Overflow
I'd suggest using a relative URL structure, so the links are all based on the current country code without needing to set it explicitly. ... <script> $(document).ready(function () { var url = window.location.pathname; var segments = url.split('/'); var countrycode = segments[1]; var hyperLink = $("a:not(.noclass)"); $.each(hyperLink, function (index, value) { var href = $(value).attr("href"); $(value).attr("href", "/" + countrycode + (href == '/' ?
Find elsewhere
🌐
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
Not sure if this helps you but it might give you a hint though it is a Java project but at least you can rely on it as it is heavily used: github.com/westnordost/countryboundaries Edit: I think that whatever solution you use, it will be more or less spoofable. ... I found GeoJSON, and know JSON, so that did help, but I needed to look it up, there are geoJSON files of earth political and states. Now just how to interpret in Javascript, X E. ... Specifically I found from that: https://www.weatherapi.com/pricing.aspx Weather API can do geolocation to country for free.
🌐
Geoapify
geoapify.com › how-to-get-user-location-with-javascript
How to Get User Location with JavaScript | Geoapify
April 1, 2026 - Using Geoapify's IP Geolocation API is simple and straightforward. You can make an API request using HTTP or HTTPS and receive a JSON response containing information about the user's location, including their country, region, city, and latitude ...
🌐
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.
🌐
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 - fetch('https://api.ipregistry.co/?key=tryout') .then(function (response) { return response.json(); }) .then(function (payload) { console.log(payload.location.country.name + ', ' + payload.location.city); }); ... AI Agents Are Great at 80% of ...
🌐
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
🌐
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 - This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020. ... The region accessor property of Intl.Locale instances returns the region of the world (usually a country) associated with this locale.
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.

🌐
CodePen
codepen.io › divya_kanak › pen › OJbpaZj
Detect Country Code From Browser
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage. All packages are different, so refer to their docs for how they work. If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing. If active, Pens will autosave every 30 seconds after being saved once. If enabled, the preview panel updates automatically as you code.
🌐
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.
🌐
HCL Software
help.hcl-software.com › dom_designer › 9.0.1 › reference › r_wpdr_runtime_locale_getcountry_r.html
getCountry (JavaScript)
Returns the country/region code for this locale, which will either be the empty string or an upercase ISO 3166 2-letter code.
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.