skip to Main Content

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


  1. 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.

    from flask import Flask, jsonify
    import requests
    import os
    
    app = Flask(__name__)
    
    @app.route('/fetch-data', methods=['GET'])
    def fetch_data():
        token = os.getenv("REST_USER_TOKEN")
        headers = {"Authorization": f"Token {token}"}
        response = requests.get("https://your-api.com/data", headers=headers)
        return jsonify(response.json())
    
    if __name__ == "__main__":
        app.run(debug=True)
    

    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:

    import React, { useEffect, useState } from 'react';
    
    const MyComponent = () => {
        const [data, setData] = useState(null);
    
        useEffect(() => {
            fetch('/fetch-data')
                .then(response => response.json())
                .then(data => setData(data))
                .catch(error => console.error("Error fetching data:", error));
        }, []);
    
        return (
            <div>
                {data ? <p>{JSON.stringify(data)}</p> : <p>Loading...</p>}
            </div>
        );
    };
    
    export default MyComponent;
    
    Login or Signup to reply.
  2. 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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search