Check If Your Site is Running on localhost

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!