I need to make a REST API call from inside the index.jsx
of a React app.
I should mention that I did not create the app, I’m just trying to put some more functionality to an already made one, so, I know the app is using webpack and everything else needed to work correctly.
I have stored the Authentication token to the .env
file and then I use it in the headers like so:
{headers: { "Authorization": `Token ${process.env.RESTUSERTOKEN}` } }
I don’t want the token value to be visible to the client, but when I View the Page Source, and consequently the app.js
from the browser, I can clearly see the full value of the token.
Is there any way to prevent this?
2
Answers
In React, storing sensitive information (like an API token) directly in .env files and then using it in frontend code can indeed lead to exposure, as you’ve noticed. Even if you reference the token using process.env.RESTUSERTOKEN, it will be accessible in the client-side code if it’s bundled with your app by Webpack.
The best approach is to use a backend to handle API requests. Instead of exposing the token in the frontend, create an endpoint in your backend server to make API requests. Your React app can then call this backend endpoint without directly exposing the token.
EDIT
Here’s a basic outline of how you could set it up:
Set up a simple Flask app to handle the requests. For example, create an endpoint like /fetch-data, which will make the actual API call using the token stored in a secure environment variable on the server.
In this example, the token is securely loaded from the environment variable on the server, so it’s never exposed to the client.
In your React app, instead of calling the external API directly, you call your Flask endpoint:
It is not secure storing your API authentication token in .env files in ReactJS.
In frontend applications, environmental variables are bundled into the final JavaScript, so they are accessible in the inspect tools.
From your backend, I would send an
HttpOnly
cookie to your React application. This way, JavaScript can’t access it on the page, which makes it more secure against cross-site scripting (XSS).