Description
After setting up .env file and installed dotenv still cant find variables and get undefined.
Expected behavior
Actual behavior
using the above step i get undefined both in my console.log aswell in the fetches were i want to use it.
i got my envVars.env file with the line
REACT_APP_REST_API_LOCATION=http://localhost:8080
and import the dotenv config in my App.js as
require('dotenv').config();
i have tried setting the require in most places in my application with same result.
Enviroment
npm: 6.0.1
react-scripts: 1.1.4
dotenv: 5.0.1
node: 6.10.3
OS: Windows 10
Packages (wanted => installed)
react: ^16.2.0 => 16.3.2
react-dom: ^16.2.0 => 16.3.2
react-scripts: ^1.1.4 => 1.1.4
you need not install dotenv. its already present through react scripts adding-custom-environment-variables
if you want to build for different environments eg: development,ed,rc,stage,live
create files .env.development, .env.ed, .env.rc etc. And in package.json create different steps for each environment
eg:
"build:ed": "cp ./.env.ed .env && npm run build"
,
"build:rc": "cp ./.env.rc .env && npm run build"
,
and place .env in .gitignore
i created an env.development file now aswell because it process.env.NODE_ENV says development but i still get undefined when trying to reach it.
here are my scripts i am currently just using npm start so what do i need to add?
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
If you have installed dotenv remove it from your package.json.
create a .env.development
(fileName starts with "." )
add property REACT_APP_REST_API_LOCATION=http://localhost:8080
try to access it using process.env.REACT_APP_REST_API_LOCATION
That solved it think i had problem with that the my filename didnt start with "."
Wanted to add that you might have to run npm build because "It works by actually replacing strings at build-time, not run-time. So each build of your application will have the values hard-coded into it." and also add REACT_APP_ to the front of any variables.
@GeorgeBelanger Thanks man I just forgot to build the app beside being faced this problem previously. I would also suggest making sure .env file is in the root and not in the src directory.
Most helpful comment
If you have installed dotenv remove it from your package.json.
create a
.env.development
(fileName starts with "." )add property
REACT_APP_REST_API_LOCATION=http://localhost:8080
try to access it using
process.env.REACT_APP_REST_API_LOCATION