1

I'm currently working with a 3rd party API, which has an API key. I am intending to store it in a .env file and have been doing it but it always comes up as undefined when I try to access it with process.env.

My .env file is keys.env which is outside of the src directory of my React JS app. I have restarted my development server, cleaned the cache of npm but my React JS app does not recognize the .env variable at all.

My File Structure:

|-node_modules<br>
|-public<br>
|-src<br>
|  .gitignore<br>
|  keys.env<br>
|  package-lock.json<br>
|  package.json <br>

My keys.env file:

REACT_APP_TEST_KEY=somekey

How the .env variable is accessed:

process.env.REACT_APP_TEST_KEY

Output:

undefined
Raju Ahmed
  • 1,282
  • 5
  • 15
  • 24
Vidarshan Rathnayake
  • 484
  • 1
  • 10
  • 20
  • 1
    Does this answer your question? [react evironment variables .env return undefined](https://stackoverflow.com/questions/53237293/react-evironment-variables-env-return-undefined) – kiranvj Nov 17 '21 at 03:44
  • Yes, tried almost everything here. – Vidarshan Rathnayake Nov 17 '21 at 03:48
  • 1
    Did you restart server after changing `.env` file? Also `keys.env` is not a valid environment file. Please check [this](https://create-react-app.dev/docs/adding-custom-environment-variables/#what-other-env-files-can-be-used). Any reason why you are using `keys.env` instead if `.env` file? – kiranvj Nov 17 '21 at 05:59
  • I tried restarting few times, and also cleared the cache. I did not try expanding the env variables as mentioned in this link. – Vidarshan Rathnayake Nov 17 '21 at 07:32

1 Answers1

1

I think you need config webpack file to use keys.env because the file name default of environment is .env

// webpack.config.js
const Dotenv = require('dotenv-webpack');
 
module.exports = {
  ...
  plugins: [
    new Dotenv({
        path: './some.other.env' // default is .env
    })
  ]
  ...
};
Mai Truong
  • 471
  • 2
  • 8
  • Thanks!. I did not follow this, instead I renamed my file to just `.env` instead of `keys.env` to get rid of the extra setup. However, according to the previous approach, this is the way to go. – Vidarshan Rathnayake Nov 17 '21 at 14:41