Check If Your Site is Running on localhost

Hero image for Check If Your Site is Running on localhost. Image by Priscilla Du Preez.
Hero image for 'Check If Your Site is Running on localhost.' Image by Priscilla Du Preez.

This Article is Over Ten Years Old...

Things can and do move very quickly in tech, which means that tech-related articles go out of date almost as soon as they have been written and published. If you are looking for up-to-date technical advice or opinion, it is unlikely that you will find it on this page.

You may find that my recent articles are more relevant, and you are always welcome to drop me a line if you have a specific technical problem you are trying to solve.

Sometimes it can be helpful to detect whether or not our web application is running on its intended domain name, or on localhost. Whilst I would suggest that using environment variables could achieve the same thing, it is easy enough to detect using JavaScript on the client side.

This can be achieved very simply by querying the window.location.hostname property, which will return the domain name of the current web page:

if (window.location.hostname === 'localhost') {  console.log('Running on localhost');} else {  console.log('Not running on localhost');}

All this code does is check the value of window.location.hostname against the string localhost. If the hostname is localhost, then the code inside the first block of the if statement will be executed. If the hostname is not localhost, the code inside the else block will be executed.

This can be more interesting if what you really want to do, is detect if your code has been copied and is being run somewhere that it shouldn't. For example, I know that the code written for this website should only ever appear in the johnkavanagh.co.uk hostname. I could write a simple utility function that looks something like this:

function codeIsStolen() {  let expectedHost = 'johnkavanagh.co.uk';  return window.location.hostname !== expectedHost;}

Easy!


Categories:

  1. Development
  2. Front‑End Development
  3. JavaScript