Search code examples
javascriptvariablesproduction-environment

How to assign a value to a a JS variable in a web site depending if it's running locally or in production?


I work on web project on my laptop. When I'm done I upload my files to production. Every time I upload to production, I've to make sure I change various URLs in my javascript code to production URLs. For example:

var ping_url = 'http://10.10.128.233'      // locally
//var ping_url = 'http://ping.service.com' // in production

I've 3 urls like this in different parts of code. I often forget to change them before uploading to production, and as a result I break production website.

Is there a way to check if I'm running the website in laptop or in production?

I'd like to write:

if (local) {
  var ping_url = 'http://10.10.128.233'      // locally
}
else {
  var ping_url = 'http://ping.service.com' // in production
}

Any ideas?


Solution

  • You could always inspect location.hostname and compare it to 'localhost' or whatever hostname you use on your laptop. For example

    var ping_url = ~location.hostname.indexOf('localhost')
        ? 'http://10.10.128.233' : 'http://ping.service.com'