Home > Blockchain >  Environment variables are not working in React app
Environment variables are not working in React app

Time:11-18

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

CodePudding user response:

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
    })
  ]
  ...
};
  • Related