Adding an .env file to a React project

Cover Image for Adding an .env file to a React project
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

Adding an .env file to a React project: A Complete Guide 😎🔑

Have you ever encountered the problem of wanting to hide your API key when committing your React project to GitHub? It can be a tricky situation, but fear not! We are here to guide you through it.

The Problem 🤔

One user on a forum had a similar issue and sought guidance on how to hide their API key in a Create React App. They followed the advice given in this Stack Overflow post, but unfortunately, their project failed to compile. Let's break down what might have gone wrong and find an easy solution.

Common Mistake: Misconfigured .env file đŸ’Ĩ

The user mentioned adding an .env file to the root of their React project, but they named it process.env. This is where the confusion arises. The correct name for the file is simply .env without any prefixes or suffixes. It is essential to ensure that the file name is exactly .env for React to recognize it.

Solution: Configuring the .env file ✔ī¸

To resolve this issue and successfully hide your API key, let's follow these steps:

  1. Create an .env file in the root directory of your React project.

  2. Open the .env file in your favorite code editor.

  3. Inside the .env file, add the following line:

    REACT_APP_API_KEY=my-secret-api-key

    ℹī¸ Make sure to replace my-secret-api-key with your actual API key.

  4. Save the changes to the .env file.

Next, let's update the fetch request in your App.js file to make use of the hidden API key.

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);
        });
}

Make sure to replace REACT_APP_API_KEY with process.env.REACT_APP_API_KEY inside the fetch request. By accessing the API key using process.env.REACT_APP_API_KEY, React will automatically replace it with the value from your .env file.

Congratulations! 🎉

You have successfully hidden your API key in your React project. Now you can commit your code to GitHub without worrying about exposing sensitive information.

If you encounter any issues or have further questions, please let us know in the comments section below. We are here to help you!


Don't forget to share this helpful guide with your fellow React developers who might be facing a similar problem. Spread the 💙 React love!

➡ī¸ Happy coding! 👩‍đŸ’ģ👨‍đŸ’ģ


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

đŸ”Ĩ đŸ’ģ 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings đŸ’Ĩ✂ī¸ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello