How to Load Environment Variables from a .env File in NodeJS
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
One way to easily store environment variables is to put them in a
.envfile. 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
.envfile to source control (i.e. Git). So, you should add it to your
.gitignorefile to make sure it's excluded from any future commits.
To achieve this, create a
.envfile in the root of your Node.js project directory:
$ touch .env
And add environment-specific variables on new lines in the form of
Here is an example:
Nice! Now we have a
.envfile 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 install dotenv --save
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")
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.envnow has the keys and values defined in your
You can test it out by logging the variable in the
When you run the code, you should see your variable's value in the command line output.
Hopefully, this was helpful in your coding endeavors.
Thanks for reading and happy coding!