Environment variables are the most important part of your backend when it comes to deployment. They store the configuration of your server and hence should never be exposed. I am going to cite an example about using the environment variables in a node application.
The package.json can be a place to store your environment variables but is not at all a secure option.
dotenv
The .env file is a special type of file used to define environment variables for your node application in a key:value format. But nodejs is unable to parse this file. Here comes dotenv which takes care of these environment variables and helps node parse the .env file.
1. Creating the file
The .env file needs to be created in the root directory of your application. This file can contain your port, jwt secret key etc.
PORT=5000
JWT_SECRET_KEY="SHHHHHHH"
2. Configuring the dotenv
First you need to install dotenv as a dev package.
npm i -D dotenv
You can use your environment variables by importing them from .env file. So far so good. Your starting point(app.js) can consider the change when you pivot from dev to prod. But if you have imported and used your environment variables in other files, this can cause you trouble unless you initialize dotenv in each file. This is a frequent mistake made by beginners. With some tweaks in your scripts used to start the application, this trouble can be fixed easily.
3. Changing scripts
You might already have 2 scripts to run your application in dev and prod:
{
"scripts": {
"start": "node app.js",
"dev": "node app.js"
// For nodemon users ====
"dev": "nodemon app.js"
}
}
We need to change the dev script so that the node knows when to use your .env file
{
"scripts": {
"start": "node app.js",
"dev": "node -r dotenv/config app.js"
// For nodemon users ====
"dev": "nodemon -r dotenv/config app.js"
}
}
And done!
Now you don't require the following lines of code in any file including your app.js/index.js .
const dotenv = require('dotenv')
const myEnv = dotenv.config()
Ensure that you ignore the file in .gitignore
Top comments (0)