What’s in YOUR .env file?
I created a React app a while ago in which users could record wildlife sightings and, by inputing the latitude and longitude of their sightings, could create pins on a map with information about the location and organism recorded (click here for the demo if you’re interested). I utilized the Google Maps API for that project and needed to request an API key. I requested my key, had fun creating my app and committed my code to GitHub. A short while later, I received an ominous email:
My frantic search to address this email led me to explore environment variables.
What is a .env file?
One thing you will quickly learn as a developer is that it is very bad practice to have an API key or client ID in your fetch call directly. You should be putting this information in a .env file; this is a file that allows you to create environment variables, which are accessible globally but can be restricted to certain “environments” (like development, production, etc). These variables are read-only and cannot be dynamically changed in your JavaScript files.
You will want to create the .env file in the root directory of your project.
In that .env file, then, you can create your environment variable. In React, there is a very specific syntax in order for your variable to be properly read.
React environment variables must be start with REACT_APP_
followed by some descriptive name (everything must be uppercase and underscores are to be used instead of spaces). They are key/value pairs and there should be NO space on either side of the ‘=’ . Finally, both key and value must be strings. Once you create your file and add your variables, make sure to RESTART YOUR SERVER.
Now, anywhere where you would need to use that variable, you would access it with process.env
followed by the variable name, like so: process.env.REACT_APP_API_KEY
Finally, in order to keep this information secure, add the .env file to your .gitignore.
This will make sure that it will not be added to your Git repository when you push the code to the repository.
Environmental variables are great for limiting the need to comb through thousands of lines of code to change very small modifications of configuration data. For example, if a URL changes and it’s stored in an environmental variable, the only place in the codebase that needs to be altered is the .env file.
Besides using the .env file to keep information secure from the public and keep code DRY, you can also use it to create multiple environments for working on code. You can set up the development environment, which you can keep separate from your production environment; the former can be serverless and can help with testing code before it goes live.
For these reasons, environmental variables are very useful and can be important additions to well-built React apps.