javascriptreactjsenvironment-variablesapi-key

Adding an .env file to a React project


I'm trying to hide my API Key for when I commit to GitHub, and I've looked through the forum for guidance, especially the following post:

How do I hide an API key in Create React App?

I made the changes and restarted Yarn. I'm not sure what I'm doing wrong—I added an .env file to the root of my project (I named it process.env) and in the file I just put REACT_APP_API_KEY = 'my-secret-api-key'.

I'm thinking it might be the way I'm adding the key to my fetch in App.js, and I've tried multiple formats, including without using the template literal, but my project will still not compile.

performSearch = (query = 'germany') => {
    fetch(`https://api.unsplash.com/search/photos?query=${query}&client_id=${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);
     });
}


Solution

  • Four steps

    1. npm install dotenv --save

    2. Next, add the following line to your app.

      require('dotenv').config()

    3. Then create a .env file at the root directory of your application and add the variables to it.

    // contents of .env
    
    REACT_APP_API_KEY = 'my-secret-api-key'
    
    1. Finally, add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub.

    If you are using Create React App (create-react-app) then you only need step 3 and 4, but keep in mind a variable needs to start with REACT_APP_ for it to work.

    Reference: Adding Custom Environment Variables

    Note - You need to restart the application after adding a variable in the .env file.

    Reference: Using the dotenv package to create environment variables