Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React env variables with .env

I'm trying to follow docs on adding env variables from react-create-app without success:

https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-custom-environment-variables

enter image description here

  • inside root of the document I have a ".env" file (default .env properties)
  • .env file contains only one variable 'REACT_APP_API_HOST=http://localhost:8080'
  • trying to access process.env inside my app (created with create react app) gives me undefined

This is app.js where I'm trying to access process.env without success.

I can't access process.env inside the code. Is there any working example on how to do it?

like image 998
Ante Avatar asked Jun 06 '17 11:06

Ante


2 Answers

You can use .env file on root.

  • start: react-scripts start - uses .env.development
  • build_staging: "set REACT_APP_ENV=staging & react-scripts build" - uses .env.staging
  • build: "react-scripts build" - uses .env.production
like image 168
Hossein Avatar answered Nov 14 '22 16:11

Hossein


In your package.json you will eventually have to add NODE_ENV=development at your start script. E.g. NODE_ENV=development && node scripts/start.js for the ejected create-react-app and NODE_ENV=development react-scripts start for the unejected one.

Edit: Apparently NODE_ENV=development is not required since it is already hardcoded when you run the start or build script. Per the docs your custom environment variables should have the following format REACT_APP* as you have already done.

A snippet would be helpful.

like image 39
john-d-pelingo Avatar answered Nov 14 '22 15:11

john-d-pelingo