How to use environment variables in Node.js

What are environment variables and why are they useful?

Environment variables are helpful in software development. Many programs and applications set or get environment variables.

Why do we need environment variables?

Security : Some things like API keys should not put in plain text in the code and thereby directly visible.

: Some things like API keys should not put in plain text in the code and thereby directly visible. Flexibility : you can reduce conditional statements à la “If production server then do X else if test server then do Y else if localhost then do Z …”.

: you can reduce conditional statements à la “If production server then do X else if test server then do Y else if localhost then do Z …”. Adoption: Popular services like GitLab or Heroku support the usage of environment variables.

Aside from default environment variables, you can also set your own. If you want to work with custom environment variables, you need to create a .env file.

How does a .env file look like?

A .env file is more or less a plain text document. It should be placed in the root of your project. You specify key value pairs and you can write single line comments using #. Here is an example how a .env file looks like:

# API

API_TOKEN=myUniqueApiToken # Database

DATABASE_NAME=myDatabaseName

How to get & set environment variables in Node.js

// get an environment variable

export const token = process.env[' API_TOKEN ']; // set an environment variable at runtime

process.env['RANDOM_ID'] = Math.random();

As you can see, an environment variable needs to be a string. If you want to store more than a simple string (e.g. an object), you could stringify the content and parse it when you need to retrieve it:

// set an environment variable at runtime which holds a user object

process.env['USER'] = JSON.stringify({

user: {email: 'someEmail@gmail.com'}

}); // get an environment variable which holds a user object

const testUser = JSON.parse(process.env['USER'])

However, you should not overdo it: do not use environment variables as a replacement for a database. I use this approach for storing some test data which should be available during the run of all the tests.

Let’s take a look how you can use custom environment variables in Node. I can recommend the dotenv module which makes it easy to load environment variables from a .env file.

How to use custom environment variables in Node

Create an .env file. The file should be placed in the root of your project Install the dotenv library: npm install dotenv . Require dotenv as early as possible (e.g. in app.js): require('dotenv').config({path: __dirname + '/.env'}) . Wherever you need to use environment variables (e.g. in GitLab, in Jenkins, in Heroku, …) you need to add your environment variables. The way depends on the platform but it is usually easy to do. Optional: create a function which runs at startup of your server. It should check whether all the required environment variables are set and throw an error otherwise.

Conclusion

Thanks for reading this article. As you can see, it is easy to work with environment variables in Node.js. How are you using environment variables? Let me know in the comments.