I'm trying to save my API key as an environment variable but I don't know how to access it... I installed dotenv using npm, created the file in the root directory and put the key there. I tried to access it in the js file by using process.env.API_KEY but it shows that the variable is undefined.
I tried putting require('dotenv').config()
at the top of the file where I need the key, but it gives me an error...
ERROR in ./node_modules/dotenv/lib/main.js 2:13-28 Module not found: Error: Can't resolve 'path' in ...
I think I may have either put it in the wrong file or I'm missing something
in conclusion:
To read the API_KEY variable in your React layer you need to export the variable REACT_APP_API_KEY before building, then in any React part you can get the value via :
See the link to see why the prefix REACT_APP_ is required.
Additionally, if your token is a long-lived or non-expirable token, it should not be exposed to the frontend (React). Only expirable tokens (AuthCodeoauth2Auth) should be exposed to the front-end layer.
Check out the references to learn how to handle front-end variables
References