visit
Setting up Environment Variables is the best practices in web dev world. But it seems troublesome for most people in practices, so few applied it. Well, it actually not that hard and it is necessary in most cases, let me show how you in this article.
Note: In this article, I will only focus on Javascript environment, I might update other languages once I figure them out later.
First at all, it is for security reasons. Obviously, you don’t want people see our “API Key” or “Encryption Slat” in our code, right?
Secondary, for better development experiences. We usually would set different databases or servers for related environment. Put those address in the code is one option, but need to switch back and forward every time we change the environments, that is a pain.
First, create .env file in project root folder, and put at least one variable there to get going (you can always add more variables when project grow). For example:
BASE_URL = //localhost:3000
NWE_VAR = 1234
Second, initial the project, start to write some code to test the environment variables.
Like example below:console.log(process.env.NEW_VAR);
Yes,
process.env
prefix is the key to access the environment variable, we can apply this rule in project-wide. At this point, we might or might not see the result (“1234”) come out from console, if yes, just skip following step, otherwise, move on.Third, install
dotenv
package into your project. # with npm
npm install dotenv
# or with Yarn
yarn add dotenv
require('dotenv').config()
Fourth, ignore
.env
file to avoid it recorded by “git” or upload to Github. Add following line to our
.gitignore
file (create one if don’t have).env
Note: This step is important and should do it as early as possible. Otherwise, all we did earlier would be useless, because “git” will log our files every time we commit.
And optionally, you might consider adding more .env files for different environments, such as:.env.development.local
.env.test.local
.env.production.local
Fifth, Setup Environment Variables in different environments.
For most cases, the server we need to run our apps already come with the support of Environment variables, such as Netlify, or Heroku. All you need to do is manually copy the values in their console panel. (It might be a way to do it in CLI, I will update it later once I found it).Setup in Netlify
Setup in Heroku
Sixth, if you still can’t manage to make the variables work, there might be some restrictions come from other factors.
For example, if the project created by create-react-app , the variable names have to start with
REACT_APP_ prefix
(more detail ), so our .env file might need to change the name as below:REACT_APP_BASE_URL = //localhost:3000
REACT_APP_NWE_VAR = 1234
yarn start