I'm working on an application utilizing the spotify API. I have secrets I want to keep in the form of Client ID's , endpoints and the like. I've done everything I am required to do to successfully use environment variables in react. This includes prefixing my variables with REACT_APP_ and making sure .env is in the root folder. In the code shown below, I am able to briefly console.log my environment variables.
const login = useRef(`${process.env.REACT_APP_AUTH_ENDPOINT}?client_id=${process.env.REACT_APP_CLIENT_ID}&redirect_uri=${process.env.REACT_APP_REDIRECT_URI}&response_type=${process.env.REACT_APP_RESPONSE_TYPE}`);
yet when I try to access them in a render here it is undefined
{!token ?
<a href={login.current}>Login to spotify</a>
:
<button onClick={logout}>Logout </button>
}
{
token ?
<form onSubmit={searchArtists}>
<input type='text' onChange={e => setSearchKey(e.target.value)} placeholder='search for a song or artist' />
<button type='{submit}'>Search</button>
</form>
:
<h2>Please login</h2>
}
}
I made sure to use a useRef hook just to make sure that the values persist so I can use my secrets when I want to return a render for react. This was to no avail. I have a feeling it has to do with when I refresh? or perhaps my environment clears after I go to my redirect URI? I also didn't bother importing dotenv because from what I've read , React handles all of that on its own. For reference here is the .env file as well:
REACT_APP_CLIENT_ID =*************************
REACT_APP_REDIRECT_URI =https://swipewithspotify.vercel.app/
REACT_APP_AUTH_ENDPOINT =https://accounts.spotify.com/authorize
REACT_APP_RESPONSE_TYPE =token
If there's some concept that I have wrong I'd love an explanation if possible or any kind of light to be sure shed on this problem.
Best way to Add env variable if we got undefined type error, I solved the same problem. Please follow these steps.
npm install dotenv-webpack --save-dev
Create .env file under root folder 3.create env variable as
REACT_APP_MY_API=342432...
Create webpack.config.js file under the root folder with the following content
add this same code into webpack.config.js file.
const Dotenv = require('dotenv-webpack');
module.exports = {
plugins: [
new Dotenv()
]
}
And you can use where do you want in your root folder or src folder
access variables like this
const apiKey = process.env.REACT_APP_MY_API;