I Am
Volodymyr Hudyma
<FrontEndDeveloper />
You Are Here: Home/Can't Read Environment Variable In React?

Can't Read Environment Variable In React?

March 26, 2021

Table Of Contents

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

    Define Environment Variable

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

    Create .env File

    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:

    Undefined In The 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 Once Again

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

    Variable Works

    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_
    Newsletter
    Receive all new posts directly to your e-mail
    No spam, only quality content twice a week
    Let me know what you think about this article
    Click here to write response...