'create-react-app .env: process not defined

create-react-app is supposed to inject your .env variables into your React app. I have used the REACT_APP_ prefix with my variables in my .env and .env.development.

However, when debugging the code I've found that process itself is undefined. So when trying to access an environment variable with process.env.REACT_APP_SOMETHING_URL, the root process variable is undefined.



Solution 1:[1]

So at the time I misunderstood how process.env works in create-react-app. I expected this to be available at runtime. However, because React is a frontend library and process is a Node backend entity you cannot directly access process.env while executing code in the browser.

This makes sense because in-browser executed Javascript doesn't know about Node; therefore, process.env isn't available.

What happens instead is that during a webpack build, webpack will inject the corresponding environment variables into your frontend asset code. So if you have a production .env file, those variables are provided during the build.

Solution 2:[2]

$ yarn add --dev react-app-env

or

$ npm install react-app-env --save-dev

Solution 3:[3]

well let me begin by saying process is an eventEmitter what lives in the nodejs world if you log it in a browser, no matter if it is angular, CRA, Vue, jquery all of them will print undefined because in the context of a browser it does not exist.

now on a CRA you is able to use process.env.YOW_VAR, basically bcuz CRA creates an Obj call process.env that is the reason behind why you need to add a prefix to them env vars which I think is REACT_APP.

  
const YOW_VARS = Object.keys(process.env)
    .filter(key => REACT_APP.test(key))
    .reduce(
      (env, key) => {
        env[ key ] = process.env[ key ];
        return env;
      },
      {
        NODE_ENV: process.env.NODE_ENV || 'development',
      }
    );

  const s = {
    'process.env': Object.keys(YOW_VARS).reduce((env, key) => {
      env[ key ] = JSON.stringify(YOW_VARS[ key ]);
      return env;
    }, {}),
  };

more or less they have something like that

Solution 4:[4]

The react-app-env package suggested on another post on this page is deprecated, as described in its repo: https://github.com/tuchk4/react-app-env

I recommend using dotenv instead.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dylan Pierce
Solution 2 Oded Ben Dov
Solution 3
Solution 4 Nilo nilold