Dotenv is a zero-dependency module that loads environment variables from a
.env
file intoprocess.env
The dotenv package is a great way to keep passwords, API keys, and other sensitive data out of your code.
It allows you to create environment variables in a .env
file instead of putting them in your code.
The steps in this file will help you add dotenv to your project. This isn't required, but it's good to know about. You generally don't want to push things like database credentials and API keys to a public repository.
You can find more information about the dotenv package here.
To start using dotenv in your project, install the package with the following command:
npm install dotenv
In your project's root directory, create a file called .env
. In this file, you can define key-value pairs to be loaded into
process.env
when your app starts. Put each variable on a new line, like this:
MONGODB_URL='mongodb+srv://<user>:<password>@<cluster>.mongodb.net/<database>?retryWrites=true&w=majority'
SENDGRID_KEY='<put your API key here>'
Any variables you define here also need to be added to your heroku app.
Go to your heroku dashboard, open your app, and click on the 'Settings' tab.
Click the 'Reveal Config Vars' button, and enter the variables you put in your .env
file.
Make sure the variable names you enter match your .env
file exactly.
Now that you have environment variables defined, you need to get them into your project.
Put this line at the top of your index.js
file with your other package requires:
require('dotenv').config()
This will require the dotenv package and load any variables defined in .env
into the process.env
object.
Now, you can use these variables instead of the hard-coded strings you were using before.
Find those strings and replace them with process.env.KEY
. For example:
const store = new MongoDBStore({
uri: 'mongodb+srv://<user>:<password>@<cluster>.mongodb.net/<database>?retryWrites=true&w=majority',
collection: 'sessions'
})
becomes
const store = new MongoDBStore({
uri: process.env.MONGODB_URL,
collection: 'sessions'
})
The last step is to make sure your .env
file is not pushed to your git repository.
If you're using the class project template, this has been done for you already.
Open (or create) your .gitignore
file (it should be in your project's root directory)
On a new line, type *.env
to exclude .env files from your git repository.
Finally, you can commit and push your changes with the following commands:
git add .
git commit -m "Add .env"
git push <your remote (heroku, origin, etc.)> master