Many developers use create-react-app to generate a boilerplate needed to quickly start developing a React application.
It gives you the option to define Environment Variables is a special file named .env.
All variables defined in this file are accessible in the code via process.env.<VARIABLE_NAME>.
First, open the project and create .env file in the root directory:
To define Environment Variable, open the .env file and paste the following code:
MY_ENVIRONMENT_VARIABLE=test
We have just defined our first variable, great.
Next, save the changes, close the file and navigate to App.jsx and read the variable:
const App = () => {
console.log(process.env.MY_ENVIRONMENT_VARIABLE);
return <div className="App">Hello, world</div>;
};
Start the project:
yarn start
And note that undefined was output to the console:
Do you know why?
The first mistake we made is not reloading our app after defining an Environment Variable.
Remember that Environment Variables are embedded during build time.
Any change in the .env file requires an application to be reloaded.
Let's do this and try again:
Still no success, let's find out why.
The second thing to remember is that, for security reasons, create-react-app does not allow you to define Environment Variables that do not start with the REACT_APP_ prefix.
Our variable name is definitely wrong and will not work.
Let's change it:
REACT_APP_MY_ENVIRONMENT_VARIABLE=test
And in the App.jsx:
const App = () => {
console.log(process.env.REACT_APP_MY_ENVIRONMENT_VARIABLE);
return <div className="App">Hello, world</div>;
};
export default App;
Reload an application and check the console:
Hooray, we got it to work.
The two most important things to remember when defining Environment Variables in a project bootstrapped with create-react-app are: