Getting environment variables into code in your web page

This is one of my “I’m putting something into the blog so that I can find it in a couple of years when I need to do this again” posts. I’m doing some work on the Connected Little Boxes website and I've been deploying the latest version. This one automatically configures a device by downloading setting information from the cloud. Code running inside the browser gets the settings from the server and then sends them into the device. To make this work the code in the browser needs to know the url of the server based data source. When I’m developing the program this will be on the localhost (my pc) and when the code is deployed the data source is the server in the cloud.

I’ve put this information in an environment variable. I have a local .env file that holds the local address. I’ve then put the deployed host address in the environment variable in the cloud. This works a treat, but I do have one problem. How do I get the value of this environment variable into the JavaScript code running in the browser? I’m using an Express web page to hold the web page source and I can embed JavaScript into the HTML but I don’t seem to be able to embed JavaScript elements into the <script> parts of the page. Probably because doing this kind if thing might disrupt the space-time continuum. So, I’ve done this… Below you can see the statement that renders the createDevice.ejs page. I pass this statement the HOST_ADDRESS environment variable that I want to feed into the JavaScript code in the createDevice.ejs page:

res.render("createDevice.ejs", { name: res.user.name, host: process.env.HOST_ADDRESS });

When the page is loaded the name and host variables are loaded with values supplied to the render method. Now, I pick those up inside the HTML and pass them into the page initialise function:

<body onload= "doStart('<%= host %>');" >

The HTML above specifies that a function called dostart will be called, and supplied with the value of host as a parameter. This is the environment variable that I want to use as the base url for my server requests.

function doStart(host) {
    console.log("starting");
    hostAddress = host;
    settingsURL = hostAddress + "createDevice/networkSettings.json"

    selectStage(stages.ConnectUSB);
  }

Above is the doStart function. It sets hostAddress with the base url for all requests and then uses this value to build the settingsURL that is used to fetch settings information from the host. It works a treat. When I run the application on my local PC the url is set to the local host and when it runs in the cloud the address is set to the cloud location. There is probably a much easier way of doing this which I don’t know about, but I’m still quite pleased with making this work myself.