The .env file can hold global variables, also known as environment variables. These variables allow you to configure your React application without having to change the source code. Furthermore, a .env file in React is a simple and effective way to securely store sensitive data. The data does not then appear directly in the source code.
It is important to note that the “.env” file format is not natively supported in JavaScript. You will need a library like “dotenv” or “dotenv-flow” to load the environment variables from the “.env” file and make them available in your code. You can install and import these libraries into your project to load the environment variables.
Projects that were created with create-react-app can already handle .env files
No import of an additional library is needed. However, the variables must begin with REACT_APP.
It is also important that the sensitive data from the .env file is not uploaded to public repositories like Github, Gitlab, etc. Therefore, the .env file should be included in the .gitignore of the project, then it will automatically be excluded from the upload to the repository.
Basically, the .env file is a simple text file that contains variables that can then be used in the project. The structure of the file can look something like this:
REACT_APP_URL=http://localhost:5000
REACT_APP_USER="ADMIN_USER"
REACT_APP_PASSWORD="ADMIN_PASSWORD"
Within your React project, you access the variables via the process.env object. As mentioned, no import
of a component is necessary if you have created the React project via create-react-app
.
So, if you want to create a link based on the REACT_APP_URL
variable, you would use the following code:
<a href={process.env.REACT_APP_URL} />
Please note that the .env file is only loaded when the project is loaded/started, such as during npm start.
So if you change values in the file, you must logically restart the project in node.js.
The .env file is also handy when it comes to switching between the development version (which usually works with localhost) and the production version. You simply create two variables and comment out the one currently not needed. Like this:
# dev variable
REACT_APP_URL=http://localhost:5000
# prod variable
# REACT_APP_URL=http://meinecooledomain:5000
The file must be placed in the main directory of the project for it to work. I have often enough created it in the src
folder and wondered why it wasn’t working. To avoid the same happening to you, here’s a screenshot 😀
Furthermore, you can find a complete description on the website of the create-react-app
project:
https://create-react-app.dev/docs/adding-custom-environment-variables/