How to check with javascript if connection is local host?

JavascriptJqueryLocalhost

Javascript Problem Overview


I want to have a check in my javascript if the page loading up is on my local machine.

The reason why I want to do that is that when I developing I like to make sure that both my server side(C#) validation is working correctly. So I like to see both the client side and server sides errors to show up.

So while I am testing I have a flag in my jquery validate stuff that just always lets invalid data go through. This way I see the client side and server errors at one go.

However right now I have to manually go and change back and forth when going from development to production.

Javascript Solutions


Solution 1 - Javascript

The location.hostname variable gives you the current host. That should be enough for you to determine which environment you are in.

if (location.hostname === "localhost" || location.hostname === "127.0.0.1")
    alert("It's a local server!");

Solution 2 - Javascript

if launching static html in browser, eg from location like file:///C:/Documents and Settings/Administrator/Desktop/ detecting "localhost" will not work. location.hostname will return empty string. so

if (location.hostname === "localhost" || location.hostname === "127.0.0.1" || location.hostname === "")
    alert("It's a local server!");

Solution 3 - Javascript

Still not a catch all but it might be a little improvement. You can now create an array of domains and use .includes

const LOCAL_DOMAINS = ["localhost", "127.0.0.1", ...];

if (LOCAL_DOMAINS.includes(window.location.hostname))
  alert("It's a local server!");

Solution 4 - Javascript

That's how it get checked in React, register service worker, good way to check if you are on localhost by checking hostname, including localhost and IPv6, and matching start with 127:

const isLocalhost = Boolean(
	window.location.hostname === 'localhost' ||
	// [::1] is the IPv6 localhost address.
	window.location.hostname === '[::1]' ||
	// 127.0.0.1/8 is considered localhost for IPv4.
	window.location.hostname.match(
		/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
	)
);

Solution 5 - Javascript

Shortest form using same mechanic as other scripts:

if ( ["localhost", "127.0.0.1", ""].includes(window.location.hostname) ) {
     console.log("It's local host !");
}

Solution 6 - Javascript

This one also covers some common cases where local network IPs start with 10.0. or 192.168. or Bonjour like domain ending on .local:

export function isLocalNetwork(hostname = window.location.hostname) {
  return (
    (['localhost', '127.0.0.1', '', '::1'].includes(hostname))
    || (hostname.startsWith('192.168.'))
    || (hostname.startsWith('10.0.'))
    || (hostname.endsWith('.local'))
  )
}

Solution 7 - Javascript

const LOCAL_DOMAINS = [ "localhost", "127.0.0.1" ];

/* offline || development */
if ( LOCAL_DOMAINS.includes(location.hostname) )
{
    BASE_URL_PUBLIC = location.hostname + "/folder/website/"; // your project folder
}

/* online || production */
else
{
    BASE_URL_PUBLIC = location.hostname;
}

Solution 8 - Javascript

An easy way to do this would be to just check the hostname against localhost or check your custom domain name against a substring, in this case ".local" urls, such as http://testsite.local

var myUrlPattern = '.local';
if (window.location.hostname === "localhost" || location.hostname === "127.0.0.1" || window.location.hostname.indexOf(myUrlPattern) >= 0) {
    alert("It's a local server!");
}

Solution 9 - Javascript

You could detect in one of your code behind pages with c#, like this:

if ((Request.Url.Host.ToLower() == "localhost"))
{
    // ..., maybe set an asp:Literal value that's in the js
}

Or if you want to do it from client script, you could check the value of window.location.host.

if (window.location.host == "localhost")
{
    // Do whatever
}

Hope this helps.

Solution 10 - Javascript

The above answers mostly solve the problem but...

  • What if localhost isn't necessarily 'localhost/'?
  • What if you want to do FE validation during development?
  • What if you want different behaviors during dev
    (fe validation, be validation, no validation)

One solution is to set the location hash and check it.

http://myname.foo.com/form.html#devValidation

You could add unlimited options with a switch

switch(location.hash) {}
    case '#devValidation':
        // log the results and post the form
        break;
    case '#beValidation':
        // skip front end validation entirely
        break;
    case '#noValidation':
        // skip all validation $('[name=validationType']).val('novalidation');
        break;
    case '#feValidation':
    default:
        // do fe validation
        break;
}

Solution 11 - Javascript

Regular expression is slower*, but short and neat. Also, nobody here checks for IPv6 localhost (::1)

/localhost|127\.0\.0\.1|::1|\.local|^$/i.test(location.hostname)

It checks for general localhost, .local domain and file: (empty hostname).

*) In Chrome, performance of [].includes(...) is the best (42 ms), followed by simple loop (for, while) with array item checking (119 ms), then [].indexOf(...) > -1 (289 ms) and finally the regexp (566 ms). But those measurements are somehow relative, because different browsers are optimized differently. In FF 52 ESR includes and indexOf have similar results, regexp is 2× slower and loop 6× slower.

Solution 12 - Javascript

Based on the above comments th following regular expression has helped me to verify if the url is 'localhost', any IP adress IPv4 or IPv6.

window.location.hostname.match(/localhost|[0-9]{2,3}\.[0-9]{2,3}\.[0-9]{2,3}\.[0-9]{2,3}|::1|\.local|^$/gi)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionchobo2View Question on Stackoverflow
Solution 1 - JavascriptUnicronView Answer on Stackoverflow
Solution 2 - JavascriptTomasz BujnowskiView Answer on Stackoverflow
Solution 3 - Javascriptdaniele bertellaView Answer on Stackoverflow
Solution 4 - JavascriptAlirezaView Answer on Stackoverflow
Solution 5 - JavascriptTarmoPikaroView Answer on Stackoverflow
Solution 6 - JavascriptHoltwickView Answer on Stackoverflow
Solution 7 - JavascriptanteloveView Answer on Stackoverflow
Solution 8 - JavascriptSummitView Answer on Stackoverflow
Solution 9 - JavascriptSamuel MeachamView Answer on Stackoverflow
Solution 10 - JavascriptShanimalView Answer on Stackoverflow
Solution 11 - JavascriptmikiqexView Answer on Stackoverflow
Solution 12 - JavascriptsaddyView Answer on Stackoverflow