How do I hide an API key in Create React App?
If you are working with Create React App and need to hide an API key, there are a few options available to you. In this blog post, we will explore two common approaches.
1. Using Environment Variables
One way to hide an API key in Create React App is by using environment variables. Create React App allows you to define environment variables that can be accessed in your code. By storing your API key as an environment variable, you can keep it hidden from the source code.
To use environment variables in Create React App, you need to prefix them with “REACT_APP_” in order for them to be recognized by the build system. Here’s an example of how you can use an environment variable to hide your API key:
{process.env.REACT_APP_API_KEY}
In the above code snippet, REACT_APP_API_KEY
is the name of the environment variable that holds the API key. You can set the value of this environment variable in a file called .env
or .env.local
in the root of your project.
2. Using a Proxy Server
Another approach to hiding an API key in Create React App is by using a proxy server. Instead of making API requests directly from your React app, you can make the requests to a proxy server, which will then forward the requests to the actual API server. This way, the API key remains hidden on the server-side.
To implement this approach, you can set up a simple Express server that acts as a proxy. Here’s an example:
const express = require('express');
const axios = require('axios');
const app = express();
app.get('/api/data', async (req, res) => {
try {
const response = await axios.get('https://api.example.com/data', {
headers: {
'x-api-key': process.env.API_KEY
}
});
res.json(response.data);
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
app.listen(3001, () => {
console.log('Proxy server listening on port 3001');
});
In the above code snippet, the API key is stored as an environment variable (API_KEY
) and is passed as a header in the request to the actual API server. The React app can then make requests to /api/data
on the proxy server instead of directly to the API server.
Remember to set up the necessary CORS headers on the proxy server to allow requests from your React app.
Conclusion
Hiding an API key in Create React App can be achieved using environment variables or a proxy server. Both approaches provide a way to keep your API key hidden from the source code. Choose the approach that best suits your needs and security requirements.
Leave a Reply