← coderrocketfuel.com

How To Load Environment Variables From An .env File In Node.js

Using environment variables is a great way to configure different parts of your Node.js application. And many packages and/or modules may exhibit different behavior based on the value of different NODE_ENV variables.

One way to easily store environment variables is to put them in a .env file. These files allow you to specify a wide range of environment variables and their corresponding values.

In most cases, you don't want to add the .env file to source control (i.e. Git). So, you should add it to your .gitignore file to make sure it's excluded from any future commits.

To achieve this, create a .env file in the root of your Node.js project directory:

touch .env

And add environment-specific variables on new lines in the form of NAME=VALUE.

Here is an example:

PASSWORD="12345"

Nice! Now we have a .env file with a variable we want to use. But how do we get that variable loaded into our code?

The easiest way is to use the npm module called dotenv. This will do all the heavy lifting for us.

You can install it with one of these commands:

NPM:

npm install dotenv --save

Yarn:

yarn add dotenv

After you've successfully installed the npm package, add the following two lines to the top of your entry file:

const dotenv = require("dotenv")

dotenv.config()

Make sure the dotenv.config() line is added as early as possible in your application to make sure all your code has access to your variables.

process.env now has the keys and values defined in your .env file.

You can test it out by logging the variable in the .env file:

console.log(process.env.PASSWORD) //"12345"

When you run the code, you should see your variable's value in the command line output.

Check out the dotenv documentation for more information.

Hopefully, this was helpful in your coding endeavors.

Thanks for reading and happy coding!