3

I am trying to add .env file and variables but I am unable to access any variable. I am using React Biolerplate Code.

I am following this React Docs File.

I have added one .env file in my root folder like this:

REACT_APP_SECRET_NAME=secretvaluehere123

And I am trying to access this using this code:

<small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small>

I am getting NODE_ENV as development but when I am trying to access:

 REACT_APP_SECRET_NAME 

I can't access it.

Mine react boilerplate is using:

cross-env  NODE_ENV=development 

in the start command.

I removed (cross-env NODE_ENV=development) from package.json but it is not working. I tried solutions from this answer: Possible answer.

According to React Docs it should work. I want to add api_url for local it should be x and for the production, it should be y:

dumazy
  • 13,857
  • 12
  • 66
  • 113
Nilay Singh
  • 2,201
  • 6
  • 31
  • 61

4 Answers4

1

The following issue from React Boilerplate seems to suggest a working solution:

  1. Install env-cmd, a node module
  2. Update your start script to use it:
  {
    start: "cross-env NODE_ENV=development env-cmd node server"
  }

This should work if your .env is in the root folder as you've said. Otherwise, you can specify the path of .env by doing so

  {
    start: "cross-env NODE_ENV=development env-cmd -f ./custom/path/.env node server"
  }
vidu.sh
  • 537
  • 1
  • 3
  • 21
0

I assume you are trying to access your .env variables inside index.html, if so then syntax is a bit different that in render function. Try to access it like this.

%REACT_APP_SECRET_NAME%
JSEvgeny
  • 2,550
  • 1
  • 24
  • 38
0

It looks like you're looking at two types of React starters:

These aren't the same. I don't know React Boilerplate, but I'm not sure if they provide the same environment variables strategy with .env files as Create React App does.

Maybe have a look at the dotenv Node package and perhaps you can add that to your project. I think (not 100% sure) that Create React App uses the same one.

dumazy
  • 13,857
  • 12
  • 66
  • 113
  • In package.json they are using: ( "start": "cross-env NODE_ENV=development node server",) They are using cross-env – Nilay Singh Dec 27 '19 at 08:26
0

Seems like you have everything right. Just remember to restart your development server every time you change information in your .env file.

Also, your .env file needs to be in the root directory of your react app. You can find all this information in the React Docs - Adding Development Environment Variables In .env

IIX
  • 11
  • 1
  • 3