Search code examples
reactjsdotenv

API Key returning undefined react


I am working to build a weather app in react, and I need to use 2 api keys. I have a .env setup and it is working fine for the first key, but I cannot seem to get my second key to return a value, it keeps showing as undefined when I make my fetch call.

My .env is setup as below. I know that the naming convention needs to include REACT_APP to be picked up but I am unsure of how to differentiate the two of them and have them still be picked up.

REACT_APP_APIKEY={MyOpenWeatherAPIKEY}
REACT_APP_APIKEY2={MyUnSplashAPIKEY} 

Any idea of how to resolve?

EDIT: For anyone having the same issue. the answer is the right way to have the keys setup in the .env file. but do not forget to kill your app and then restart it after making changes to the .env file.


Solution

  • try this inside your .env :-

    REACT_APP_OPEN_WEATHER_KEY=whateveryouropenweatherkeyis
    REACT_APP_UNSPLASH_KEY=whateveryourunsplashkeyis
    

    note that curly braces are not required here

    then you can access them anywhere in your code like this : process.env.REACT_APP_OPEN_WEATHER_KEY , process.env.REACT_APP_UNSPLASH_KEY

    NB : make sure .env is in the root project directory i.e. same with package.json