
Check If Your Site is Running on localhost

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:
Related Articles

Five Tips on How to Be a Good Web Developer. Where to Find Jobs in Web Development. Where to Find Jobs in Web Development

Understanding the Nullish Coalescing (??) Operator in JavaScript. Understanding the Nullish Coalescing (
??) Operator in JavaScript
Understanding prototype.apply() in JavaScript. Understanding
prototype.apply()in JavaScript
Implementing Server‑Side Rendering (SSR) in Vue. Implementing Server‑Side Rendering (SSR) in Vue

Ethical Web Development ‑ Part I. Ethical Web Development ‑ Part I

JavaScript Essentials for Freelance Web Developers. JavaScript Essentials for Freelance Web Developers

Array.includes() vs. indexOf() in JavaScript. Array.includes()vs.indexOf()in JavaScript
Optimising Angular Forms: Template‑Driven vs. Reactive Forms. Optimising Angular Forms: Template‑Driven vs. Reactive Forms

Angular Change Detection: How It Works and How to Optimise It. Angular Change Detection: How It Works and How to Optimise It

Trigonometric Functions in CSS. Trigonometric Functions in CSS

The React Context API: When to Use It and When Not to. The React Context API: When to Use It and When Not to