You might find many tutorials on the internet for learning coding and development, you start with basics and soon you find yourself overwhelmed by the features and complexities. You realize that if you try to build all the features on your own then it’s going to be a humongous task. Thus you go for many service providers for services like emailing, text messaging, monitoring, source code management etc.
In order to use all these services, you would sign up for their APIs and hence receive access to these APIs. With these APIs, you may get secret Auth Tokens/API Secrets/API Keys etc. You have to incorporate these keys and tokens in your code to use these services. Following are some methods of managing environment variables:
1. The Naive Approach:
Basically, you just hard code them in your code base, which is a naive and insecure approach that most of us use to incorporate these secrets while learning and working on your example projects.
If you are using Twilio for sending SMS to your newly signed up users to verify their phone number, then you might end up hard-coding your secrets like below.
This approach is a really bad idea as you will be exposing all your keys and tokens to everyone who has access to your code base (even just read permissions). If these auth parameters get changed/renewed, you will have to change it everywhere on your own by the tedious hunt, seek and change method.
2. Export all secrets to your shell:
Alternatively, you can store all your variables as shell variables that will be available to your running code or even better put all your secrets/tokens in your .bash_profile/.bashrc and then you source this file due to which these will be available to all your running processes via environment variables. This solves your DRY(Do not Repeat Yourself) problem.
Above command will make a variable PORT with value 9999 available to server.js and for the example of Twilio you can put your secrets in your .bash_profile/.bashrc like
It might be possible that two different projects are using same API secrets/tokens but with different values then you have to change them again and again according to the project you are working on.
3. Maintain .env for each project:
The best approach to maintain your Auth Tokens/API Secrets/API Keys etc is to keep an environment file for each of your projects so just make a .env file (you may name it differently) and put all the secrets in this file.
And make sure to put your .env file in .gitignore so that this file is not present in your codebase and maintain it independently on your server.
To run the process just source your .env file.
And in this way, you can maintain all your API secrets/tokens and other tokens/keys in your environment and keep them safe and secure.