Environment variables are basically variables you stored on your own machines, instead stated directly in your source codes.
You can think it in this way, instead of stating a variable in the source codes like the following.
let name = "XinYang-YXY"
You can store the variable and its value on your own machine and import the variable to your source codes like the following
process.env.name
But why we want to do so? Isn't it an extra step? One simple but critical reason is SECURITY.
Imagine uploading your source codes to Github and open source it. People around the world can know all your API keys easily by just looking through your source codes.
If they are malicious, they can use your API keys for their own usage. And you have to pay for all the requests they generated using your API keys. You definitely don't want that to happen to you.
That is why you want to use environment variables. When your source codes running locally, it is able to use import codes to import the API key value into your source codes and carry out the task.
When the source codes are uploaded to Github, people can only see the import codes and don't know what is your API key. Isn't it amazing?
Now I will teach you how to use environment variables inside your NodeJS application.
First, you will need to install an npm package called 'dotenv'
npm install dotenv
Second, you need to create a dotfile aka a hidden file called '.env' at the root of your application. This is the file where you place all your environment variables - all your little secrets.
Third, you can place state all your environment variables inside the dotfile like the following
After that, it is time to import the environment variables into your source codes! Open the file you need to use the values stored in the environment variables.
require("dotenv").config(); // Import the .env file you created at the root of the project
module.exports = {
host: process.env.DBHOST, // same as host: "mydb.com"
database: process.env.DBNAME, // same as host: "db"
username: process.env.DBUSER, // same as host: "admin"
password: process.env.DBPASS, // same as host: "mypassword"
};
When you upload your source codes to Github, the '.env' file is by default not uploaded. So all your little secretes can stay private!
Well done! That is all you need to do to create and use environment variables in your NodeJS project. Feel free to comment below if you have any questions. Have fun hacking!
Top comments (0)