Building web apps with React would normally require access to an API to fetch some data to be displayed as the user interface of your application.
To have access to the API endpoint, you will first need to have an API key. The API Key is a code used to identify and authenticate the user to enable him to perform some actions on the external application.
Because you will be connecting to the external app using the key, the API Key will be in the source code of your app. The danger is, when the code is published on a code hosting platform like GitHub, other users can have access to the key, and use your key to perform certain actions not authorized by you.
There is therefore the need to secure your API Key before pushing your code to the public repository.
In this article, I will take you through the steps to take to hide your API Key when publishing your code on a public repository.
Let's get started
Creating an environment variable
Environment variables help us to store sensitive information such as passwords and API credentials, which you don't want others to have access to when you publish your code on the code hosting platform.
It also helps keep your sensitive credentials in one location, and use it in multiple files without having to keep copying it, you can change the credentials at that single location, and the effect will be replicated anywhere the credential is being used.
Let's see how to create an environment variable in React apps.
How to create a .env
file
If your project is created with create-react-app, follow the steps below
- Create a
.env
file at the root of your project - Declare your environment variable, with the prefix:
REACT_APP_
- Append any other name after the prefix, for instance
RAPID_API_KEY
- The full environment variable name, will be
REACT_APP_RAPID_API_KEY
- Remember that variable name should always begin with
REACT_APP_
, so the format should beREACT_APP_YOURCUSTOM_VARIABLENAME
- Assign the API Key to the declared variable. For instance
REACT_APP_RAPID_API_KEY= 1234212343
Using the .env file
To use the .env
file created in the above steps
- Go to the file from which you want to connect to the API endpoint
- Use it by following the format
process.env.REACT_APP_CUSTOM_VARIABLENAME
- Using our instance, the format to connect to the RAPID API endpoint will be
process.env.REACT_APP_RAPID_API_KEY
-
Restart your app using
npm start
and refresh your application - Your app is now connected to the API endpoint
Conclusion
In this article, we have learned how to create an environment variable or .env
file in React to store our sensitive information. Now, when you commit your code and push it to a code hosting platform, the API Key will be hidden.
Have you had any instance where you push your API Key to public code hosting platform, what did you do afterwards ?
If you find any usefulness in this post, don't forget to share on your social media platform, it will be of great help to others.