How to setup Environment Variable in React.js

In today’s tech-driven world, web developers often find themselves facing challenges related to security and sensitive data management, especially when working with APIs. A common issue is how to hide an API key in a Create React App project while also making the code easily shareable on platforms like GitHub. In this tutorial, we’ll explore how to tackle this problem by adding an .env file to your React project.

Problem Statement:

Suppose you are building a React application that relies on an external API for data. To access this API, you need to provide an API key, but you want to keep this key secure and not expose it in your project’s code, especially when you push your code to GitHub.

Solution:

To address this issue, you can follow these steps:

Step 1: Create an .env File

In the root directory of your React project, create a file named .env. This file will contain your environment variables.

REACT_APP_API_KEY='my-secret-api-key'

Ensure that your environment variable names start with REACT_APP_, as this is a requirement for React to recognize them.

Step 2: Access the Environment Variable

Now that you’ve defined your environment variable in the .env file, you can access it in your code using process.env.REACT_APP_API_KEY. For example, in your App.js file:

performSearch = (query = 'germany') => {
    fetch(`https://api.unsplash.com/search/photos?query=${query}&client_id=${process.env.REACT_APP_API_KEY}`)
    .then(response => response.json())
    .then(responseData => {
        this.setState({
            results: responseData.results,
            loading: false
        });
     })
     .catch(error => {
            console.log('Error fetching and parsing data', error);
     });
}

By using process.env.REACT_APP_API_KEY, you can safely access your API key without exposing it in your code.

Step 3: Restart Your Application

After adding or modifying environment variables in the .env file, it’s crucial to restart your development server. This ensures that the changes are picked up by your application.

npm run start

Step 4: Keep the .env File Secure

Remember to add the .env file to your .gitignore to prevent it from being pushed to your GitHub repository. Keeping your API keys and sensitive information out of version control is essential for security.

Conclusion:

By following these steps and adding an .env file to your React project, you can securely manage API keys and other sensitive data while maintaining the convenience of sharing your code on platforms like GitHub. This practice not only enhances the security of your application but also ensures that your development process remains efficient and collaborative.

Bipul author of nerdy tutorial
Bipul

Hello my name is Bipul, I love write solution about programming languages.

Articles: 146

Leave a Reply

Your email address will not be published. Required fields are marked *