Can’t Read Environment Variables In React?

Can't Read Environment Variables In React?

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..

Define Environment Variable

First, open the project and create .env file in the root directory:

env var on root

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.js and read the variable:

const App = () => {
    console.log(process.env.MY_ENVIRONMENT_VARIABLE);
    return <div className="App">Hello, world</div>;
};

Start the project: NPM START

And note that undefined was output to the console:

undefined console

Do you know why?

Gotcha #1

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:

undefined console

Still no success, let’s find out why.

Gotcha #2

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.js:

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:

working console

Hooray, we got it to work.

Summary

The two most important things to remember when defining Environment Variables in a project bootstrapped with create-react-app are:

  • Always reload your application after making a change to the .env file
  • Always prefix your variables with REACT_APP_