Hiding & loading API keys into specific end points has been a measure issue in React, if they are being saved as variables, the load time and optimization may not equal to the time it takes the useEffect to load hence we have environment variables.
We also don't want to display our API key to the public to avoid malicious attacks so we use environment variables (.env file) and add it to the git ignore so when we push to github the API key/access token is not open.
Your project can consume variables declared in your environment as if they were declared locally in your JS files. By default you will have NODE_ENV defined for you, and any other environment variables starting with REACTAPP.
The environment variables are embedded during the build time. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime.
Note: You must create custom environment variables beginning with REACTAPP. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.
These environment variables will be defined for you on process.env. For example, having an environment variable named REACT_APP_NOT_SECRET_CODE will be exposed in your JS as process.env.REACT_APP_NOT_SECRET_CODE.
We start by creating a .env
file, the location is extremely important (for React apps) we don't but the .env
file in the src
folder, we put it in the root of the whole app structure/folder.
Once we are done creating the .env
file we can now enter into the codes by
// The prefix must always be REACT_APP_
REACT_APP_ACCESS_KEY="What ever your access key is"
So it's time we access our env variable in our app.js or anywhere in our maybe
const clientID = `?client_id=${process.env.REACT_APP_ACCESS_KEY}`;
//We can use this method to add
//Access key to our routing url
Note anytime we set a
.env
we must restart the server by going to our terminal and writingCTRL C
to stop the server andnpm start
to start again
And that's it, it's that simple. Happy Coding!!!