Luiz E. Luiz E. - 2 months ago 16
React JSX Question

read environment vars in a simple react app

I create an app with

create-react-app
module, and in a component, I'm trying to read an env. var, like this

<p style={textStyle}>Environment: { process.env.AWS_ENV || process.env.NODE_ENV }</p>


I start the app with
AWS_ENV=live npm start
and it never reads this var. the result is always
development
. I noticed tho, if I build the app with
npm run build
, the output will be
production
, but anyway I cannot read the AWS_ENV var

Answer

create-react-app using https://github.com/motdotla/dotenv. To load ENV into Webpack and to pass it in browser, run this commands in console:

echo -e 'REACT_APP_AWS_ENV=live' > .env
npm start

Note REACT_APP_ prefix special to create-react-app.

Then in your components:

...
{ process.env.REACT_APP_AWS_ENV }
...