4

I cannot use my environment variables on my development (localhost) with ReactJS.

I made sure of following:

  1. My .env file is in the root directory
  2. My env variable has a prefix of REACT_APP_* and the usage is process.env.REACT_APP_*
  3. My env variable does not contain '' and contains = as well as it does not contain ; or , so the definition is REACT_APP_SOMETHING = something
  4. Restarted server multiple times by ctrl + c and yarn start
  5. I checked (and copied & pasted) all the variable names to make sure and avoid misspelling

Even after all of this if I try to use them (for example with console.log(process.env.REACT_APP_SOMETHING)) it prints only undefined. Is there anything that has to be done in package.json scripts? The definition is only:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

I used create-react-app to initialize my project.

Printing for example console.log(process.env.NODE_ENV) works fine. I tried even creating .env.development file with no luck.

tomdelahaba
  • 948
  • 3
  • 13
  • 26

1 Answers1

1

After hours of trying, searching and crying, solution found...

The problem was in Visual Code (using macOs). I created the file (.env) inside Visual Code. But this (somehow) did not create the file inside the project folder! After listing all files (including the hidden ones) inside the project folder (ls -a) I found out the file .env was missing even when Visual Code was showing that file.

Creating the file inside terminal (touch .env), another file appeared in the project folder in Visual Code and after putting all my environment variables into this file, everything started working.

This is really weird as .git file was created without problems. Lost few hours of my life on this one...

tomdelahaba
  • 948
  • 3
  • 13
  • 26
  • I got the same problem as you described. Mac os doesn't allow me to create the file that starts with '.' in that folder so I opened the project via Brackets editor and created .env file. The problem was fixed! – Oksana B Jul 26 '23 at 11:25