8

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?

6
  • Is NODE_ENV defined in your path? Commented Jun 6, 2017 at 12:00
  • No, but .env as a default is defined. Commented Jun 6, 2017 at 12:01
  • 2
    Ah weird! Are you able to access any other variable using process.env by exporting it in bash profile? Commented Jun 6, 2017 at 12:08
  • 1
    Can you share your code? Commented Jun 6, 2017 at 12:15
  • 7
    After you add new .env variable, make sure to restart yarn. Also, your custom .env variables should start with REACT_APP_ Commented Jun 6, 2017 at 12:34

2 Answers 2

16

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Issue was that I was trying to read it while in debug mode by watching variables. For some reason, it does not work. By simply console logging it, it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.