How to read environment variables in Node.js?

This post is 4 years old. (Or older!) Code samples may not work, screenshots may be missing and links could be broken. Although some of the content may be relevant please take it with a pinch of salt.

Sometimes it is necessary to use environment variables in Node.js - a classic example is when we have some code that is doing more debugging when executed on a development platform vs when it's executed on a production platform. This information may be stored in an environment variable so Node.js would have to get this information.

Another example is when providers such as DigitalOcean give you apikeys, usernames and passwords via environment variables. Furthermore, secrets used for hashing (say for JWT tokens) should also be used as environment variables.

In order to access an environment variable we can utilise the process.env object and access the properties on that object. The properties do reflect the environment variables.

We can see what environment variables we have available for Node.js by creating a very simple application:

console.log(process.env);

Execute the above and see a list of environment variables.

If you're on *nix you can easily create some additional environment variable and access that as well:

(It goes without saying that you can create environment variables on Windows as well and access them)

$ export SECRET='h3ll0'

And now we can access SECRET:

console.log(process.env.SECRET); // h3ll0

Of course we can not only log these values out but we can utilise them in our code too.