Modern web applications rely on external APIs for added functionality.
Some APIs use identifiers like keys and secrets to associate requests with a particular software.
This tutorial will teach you how to safely store and access API keys in a React app.
It reads variables that begin with REACT_APP and makes them available through process.env.
This is possible because the dotenv npm package comes installed and configured in a CRA app.
Ensure you add .env to the .gitignore file to prevent git from tracking it.
React embeds it in the build files, which means anyone can find it by inspecting your apps files.
Instead, use a backend proxy that calls the API on behalf of your front-end tool.
For example, theAPI endpoint below fetches datafrom a secret URL.
Call this API endpoint to fetch and use the data in the front end.
Using Next.js to Store Environment Variables
Another alternative is to use Next.js.
you’ve got the option to access private environment variables in the getStaticProps() function.
This function runs during build time on the server.
So the environment variables you access inside this function will only be available in the Node.js environment.
Below is an example.
Code in these endpoints runs on the server, so you might mask secrets from the front end.
For example, the above example can be rewritten in thepages/api/getData.jsfile as an API route.
you’re free to now pull up the returned data through the/pages/api/getData.jsendpoint.
Keeping API Keys Secret
Pushing APIs to GitHub is not advisable.
Anyone can find your keys and use them to make API requests.
By using an untracked .env file, you prevent this from happening.
Instead, fetch the data on the server side or use Next.js to mask private variables.