Announcing JavaScript Environment Variables

Environments are a first-class feature of the Divshot hosting platform. From day one we've supported development, staging, and production as facets of the same application. Today we're leveling up the usefulness of those environments by introducing JavaScript environment variables.

How it Works

If you have configuration variables that change between your environments, simply add them using the command-line interface. For example, if I wanted to vary my Google Analytics key between environments I could do this:

divshot env:add staging ANALYTICS_KEY=UA-STAGINGXXX
divshot env:add production ANALYTICS_KEY=UA-PRODXXX

Once you've added variables to your environment, there are two ways to access them in your application:

  1. By making an AJAX request to /__/env.json, which will be a simple JSON object with keys and values as you'd expect.
  2. By adding <script src="/__/env.js"></script> to any HTML page. This will set an __env variable on your window object that should be accessible anywhere.

To follow through on our earlier example, here's how we might implement our environment variables with Google Analytics in our HTML:

    <script src="/__/env.js"></script>
    <script type="text/javascript">
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', __env.ANALYTICS_KEY]);
      // ... GA configuration continues

Now when you access your site on production and staging, your property will be set appropriately without you having to worry about building or deploying things differently.

Local Configuration

Of course you will likely want to use environment variables locally as well. Easy! Just create a .env.json file in your project's directory and populate it with your local configuration! For example:


When you run divshot server this file will automatically be picked up and served just like environment configuration on hosted environments (it also works with superstatic, our open-source static server).

Why it Matters

We believe your front-end code deserves a platform that takes it seriously. Environment configuration will make your application more flexible, more easily testable, and less prone to human error. No more "Oh no! I just deployed development code to production!". No more "I guess I'll check window.location and configure things based on that." Just simple, reliable access to the configuration you need.

Note: There's more fun stuff you can do like pulling down configuration from your app to your local machine. Check out the documentation for the details.