Environment variables is a widely used term, but what does it actually mean and why does it even exist ?
Technical Definition: An environment variable is a dynamically set value that is used throughout program and determines properties of a program on each device. They are part of the environment in which a program executes.
For example, a program can get the values for a specific key from environment variables, say Proxy to go through a proxy tunnel while making network requests if proxy variable exists.
Benefits of environment variables are –
- Easy maintenance and adaptive code
Let’s understand it with the help of another example. Imagine, you get a paid service like a paid weather API service and got a secret token for authentication which you included in your weather project.
const weather_api_key = "YourVeryUsefulAndSecretToken";
Now, you made a public repository for this project like most of us do. But wait, this means anybody can use your key in their projects while you’re paying for it. That’s a big issue !
So, should you stop keeping your project in public repositories?
No ! You should always try to add your projects to Github or similar VCS services to enhance your portfolio. We just need a way to isolate this secret key from plain code, yet usable in the code. The answer is Environment variables.
Environment variables are a set of key-value pairs setup on the local setup or hosting service, rather than direct inclusion in plain code, which are usable in your code,
const weather_api_key = process.env.weather_key;
Where the weather_key refers to the actual token value i.e. “YourVeryUsefulAndSecretToken”
Edit and add .env or other files with environment variables in the .gitignore file, so that it remains untracked by git. You can push this code to your repositories without any security concerns now !
Environment variables solved the security issue, but it has another benefits too. Environment variables ensure Adaptive code.
For example, if the code uses the above mentioned environment variable named support_email wherever it has to display support email on the website. Later you wish to change it due to some reasons. In such cases, you just need to change it in environment variables configuration. Had it been as a plain code, It would be a tedious task to change it everywhere.
Setting up environment variables differs based on your Operating System and Hosting services, so get help from your service-specific docs or guides. Environment variables are generally scoped globally across the Operating System, but there are some ways to set up environment variables specific for your project too. Checkout this article on setting up environment variables in Node JS.