Search code examples
node.jsvisual-studioazuredeploymentazure-cloud-services

Environment variables not being set when deploying to Azure Cloud Service via Visual Studio


Having a few issues with environment variables in Azure Cloud Services. I'm trying to set a "NODE_ENV" environment variable during deployment via the ServiceDefentition.csdef file.

The variable is to be read in by my node.js app via process.env.NODE_ENV.

The documentation for this isn't very extensive (as it appears to be a very simple thing to do) but this is what I have been following: link1 link2

The section of the ServiceDefinition file I have is the following:

<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="userApiServer" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" schemaVersion="2015-04.2.6">
  <WebRole name="userApiWebRole" vmsize="Large">
    ...
    <Runtime>
      <Environment>
        <Variable name="NODE_ENV" value="dev" />
      </Environment>
    </Runtime>
    ...
  </WebRole>
</ServiceDefinition>

I've tried numerous variations; setting the env variable under a startup task instead on runtime, using xpaths to configuration settings but they just don't seem to be creating the env variables for me.

When messing around with the xpaths approach I did find that my configuration settings were being created on the instance, so the definition file is being read.

Are there any common (or uncommon) gotcha's or hidden details that I'm missing because for something apparently very simple I'm having a lot of trouble with it.


Solution

  • It is correct to set node_env variable in web.config and iisnode.yml as @AIDAN CASEY said.

    Additionally, we can leverage pure Node.js 3rd part module dotenv. Just need to create a file named .env with the content:

    node_env=production
    

    include and initialize the module in Nodejs script:

    require('dotenv').load();