tomdelahaba
tomdelahaba

Reputation: 1048

ReactJS Environment variables are undefined on development

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.

Upvotes: 4

Views: 2991

Answers (1)

tomdelahaba
tomdelahaba

Reputation: 1048

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...

Upvotes: 1

Related Questions