Menu
Working with environment variables is a great way to configure different aspects of your Node.js application. Many cloud hosts (Heroku, Azure, AWS, now.sh, etc.) and Node.js modules use environment variables. Hosts, for example, will set a
PORT
variable that specifies on which port the server should listen to properly work. Modules might have different behaviors (like logging) depending on the value of NODE_ENV
variable.Here are some of my tricks and tools when working with environment variables in Node.js.
Use npm link to do this. Install: It’s a good idea to install things if you don’t need the symbolic link. Especially, installing other peoples code from the registry is done via npm install adduser: Create an account or log in. Credentials are stored in the user config file.
- Jul 26, 2019 NCM Integration to NPM. On the Orion NPM Web pages, why do users require 'view customization rights' to add NCM credentials? Maybe I did something wrong? Otherwise, I really can't afford to have every user who needs access to their configs to have the 'view customization rights'.
- Get unlimited public & private packages + package-based permissions with npm Pro.
- First we create routes for a wiki in a module named wiki.js. The code first imports the Express application object, uses it to get a Router object and then adds a couple of routes to it using the get method. Last of all the module exports the Router object.
- Jul 21, 2016 I was researching what our upgrade path would be to NPM 12 and had a question. Using the Upgrade Advisor, it says I upgrade NPM to 11.5.2 to 12.0 and then upgrade NTA from 4.1.1 to 4.2.
The Basics
Accessing environment variables in Node.js is supported right out of the box. When your Node.js process boots up it will automatically provide access to all existing environment variables by creating an
env
object as property of the process
global object. If you want to take a peek at the object run the the Node.js REPL with node
in your command-line and type:This code should output all environment variables that this Node.js process is aware of. To access one specific variable, access it like any property of an object:
You should see that the value of
PORT
is undefined
on your computer. Cloud hosts like Heroku or Azure, however, use the PORT
variable to tell you on which port your server should listen for the routing to work properly. Therefore, the next time you set up a web server, you should determine the port to listen on by checking PORT
first and giving it a default value otherwise:The highlighted line will take the value of the
PORT
if it’s available or default to 3000
as a fallback port to listen on. Try running the code by saving the it in a file like server.js
and run:The output should be a message saying
Server is listening on port 3000
. Stop the server with Ctrl+C
and restart it with the following command:Mac dmg to usb windows 10. However, FAT32 can be only used for installing OS with legacy BISO, which doesn't work for macOS. So the next step is to format your USB drive in the in order to burn installation files to the desired USB drive.
The message should now say
Server is listening on port 9999
since the PORT
variable has been temporarily set for this execution by the PORT=9999
in front of node
.Since
process.env
is simply a normal object we can set/override the values very easily:The code above will set or override the value of
MY_VARIABLE
. However, keep in mind that this value is only set during the execution of this Node.js process and is only available in child processes spawned by this process. Overall you should avoid overriding environment variables as much as possible though and rather initialize a config variable as shown in the PORT
example.Explicitly loading variables from .env
files
If you develop on multiple different Node.js projects on one computer, you might find you have overlapping environment variable names. For example, different messaging apps might need different Twilio Messaging Service SIDs, but both would be called
TWILIO_MESSAGE_SERVICE_SID
. A great way to achieve project specific configuration is by using .env
files. These files allow you to specify a variety of different environment variables and their values.Typically you don’t want to check these files into source control so when you create one you should add
.env
to your your .gitignore
. You will see in a lot of Twilio demo applications .env.example
files that you can then copy to .env
and set the values yourself. Having an .env.example
or similar file is a common practice if you want to share a template file with other people in the project.How do we load the values from this file? The easiest way is by using an npm module called
dotenv
. Simply install the module via npm:Afterwards add the following line to the very top of your entry file:
This code will automatically load the
.env
file in the root of your project and initialize the values. It will skip any variables that already have been set. You should not use .env
files in your production environment though and rather set the values directly on the respective host. Therefore, you might want to wrap your load statement in an if-statement:With this code we will only load the
.env
file if the server isn’t started in production mode.Let’s see this in action. Install
dotenv
in a directory as shown above. Create an dotenv-example.js
file in the same directory and place the following lines into it:Afterwards, create a file called
.env
in the same directory with this content:Run the script:
The output should look like:
As you can see the value was loaded and defined using
dotenv
. If you re-run the same command with NODE_ENV
set to production
you will see that it will stay undefined
.Now the output should be:
If you don’t want to modify your actual code you can also use Node’s
-r
argument to load dotenv
when executing the script. Change your dotenv-example.js
file:Now execute the file first normally:
The script should print that the current value for
FOO
is undefined
. Now execute it with the appropriate flag to require dotenv
:The result is that
FOO
is now set to bar
since the .env
file has been loaded.An alternative way to load .env
files
Now
dotenv
is great but there was one particular thing that bothered me personally during my development process. It does not override existing env variables and you can’t force it to do so.As a result of these frustrations, I decided to write my own module based on
dotenv
to fix this problem and make loading environment variables more convenient things. The result is node-env-run
or nodenv
. It’s a command-line tool that will load a .env
file, initialize the values using dotenv
and then execute your script.You can install it globally but I recommend to only use it for development purposes and locally to the project. Install it by running:
Afterwards create a file
nodenv-example.js
and place this code in it:As you can see, we don’t need to require anything here. It’s just the application logic. First try running it using
node
:This executed code should output
The value for FOO is: undefined
. Now try using node-env-run
by running:The result should be
The value for FOO is: bar
since it loaded the .env
file.Npm Create New
node-env-run
can override existing values. To see it in action first run the following command:The command-line output should say
The value for FOO is: foo
. If we now enable force mode we can override existing values:As a result we should be back to the original
The value for FOO is: bar
.If you want to use this tool regularly, I recommend that you wrap it into an npm script. By adding it in the
package.json
like so:This way you can simply run:
Environment variables && npm scripts
Create Npm Project
There are scenarios where it’s useful to check the value of an environment variable before entering the Node.js application in npm scripts. For example if you want to use
node-env-run
when you are in a development environment but node
when you are in production
mode. A tool that makes this very easy is if-env
. Install it by running:Make sure to not install it as a “dev dependency” since we will require this in production as well.
Now simply modify your npm scripts in your
package.json
:This script will now execute
npm run start:prod
and subsequently node .
if NODE_ENV
has the value production
and otherwise it will execute npm run start:dev
and subsequently nodenv -f .
. You can do this technique with any other environment variable as well.Try it out by running:
Debugging
We all know the moment where things are just not working the way you want it to and some module is not doing what it’s supposed to do. That’s the moment it’s time for debugging. One strategy that helped me a lot is using the
DEBUG
environment variable to receive more verbose logs for a bunch of modules. If you for example take a basic express
server like this:Plus, with the customizable “House Rules”, you’ll be able to change up the challenge any way you like. Monopoly 1.0.1 dmg.
And start it up with the
DEBUG
variable set to *
:You’ll receive a bunch of extensive logging that looks something like this:
The “magic” behind it is a lightweight module called
debug
and its usage is super easy. When you want to use it all you have to do is to initialize it with a “namespace”. Afterwards you can log to that namespace. If someone wants to see the output all they have to do is enable the namespace in the DEBUG
variable. express
in this case uses a bunch of sub-namespaces. If you would want everything from the express
router, all you have to do is set DEBUG
with the appropriate wildcard:If you want to use
debug
in your own module all you have to do is to first install it:And afterwards consume it the following way:
Now use all the environment variables!
These are by far not all the things you can do with environment variables and all the tools that exist but rather just the ones that I use most often. If you have any other great tools that you regularly use, I would love to hear about them!
- Email: [email protected]
- Twitter: @dkundel
- GitHub: dkundel
Now that you’ve learned a bit more about Environment variables in Node.js, try out Twilio’s Node.js quickstarts!
Please enable JavaScript to view the comments powered by Disqus.