Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Hiding Secret Keys in Create-React-App

Jun 15, 2020 • 5 Minute Read

Introduction

Have you ever wondered how to avoid publishing your secret keys when you make your code public on places like Github? This guide focuses on helping you protect your secret keys in create-react-app. To make this practical, you'll set up an app that makes an API call to Newsapi.org and secure the keys obtained from the API provider. These features work only with react-scripts@0.5.0 and higher.

Set up Create-React-App

The first step is to set up a React app. Open a terminal/shell and run these commands to get a create-react-app project set up.

      npx create-react-app react-secret-keys
    

After create-react-app completes installation, enter this command in your terminal:

      cd react-secret-keys
yarn start
    

The development server for create-react-app should be running on localhost:3000. Open your browser and you should see the React Logo. Go to newsapi.org and sign up to get an API key.

The Unsafe Way

The code snippet below shows how you would make an API call with the key obtained without thinking of security. If you should publish this key to Github, anyone who views your code would have access to your key. That's not good!

      const API_URL = "https://newsapi.org/v2/everything?q=usa&apiKey=
OW09823D03ASE48F34RUNF83"; // <- API_KEY inlined in the url

function App(){    
     const [newsList, setNewsList] = useState([]);    
    useEffect(() => {          
      getNews(); 
}, []);   
const getNews = () => {      
fetch(API_URL)          
.then(response => response.json())              
.then(data => setNewsList([...data])
;} 
return (  
 <div>    
      { newsList.map( item => <p key={Math.random()}>{item.headline.title}</p> )} 
 </div>)
    

The Safe Way

To secure the key you obtained from Newsapi, create a .env file at the root of your project. Your project structure should be similar to this:

      -react-secret-keys

 -node_modules

 - public 

 - src 

 - .env  ←Right here

 - .gitignore

 - package-lock.json

 - package.json
    

Add API Key

to .env File create-react-app automatically reads keys that begin with REACT_APP and defines them on process.env (create-react-app embeds the keys at build time). To add your API_KEY simply prepend it with REACT_APP and add it to your .env file. You have to restart the development server if it is running (Use Ctrl+c or Cmd+c in your terminal where your development server is running and enter the command yarn start again) .

Adding your secret key to the .env file doesn't prevent your key from being public in production. The create-react-app documentation states that clearly.

WARNING: Do not store any secrets (such as private API keys) in your React app!

Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.

One way to solve this is to make your app request data through a backend (node + express) but that is beyond the scope of this guide. In short, avoid storing mission critical API keys on your frontend.

      // .env
REACT_APP_API_KEY = OW09823D03ASE48F34RUNF83
API_KEY  = OW09823D03ASE48F34RUNF83 // <- This would not be discoverable on process.env
    

Add .env to .gitignore

Make sure you add your .env file to your .gitignore file at the root of your project folder (react-secret-keys) to ensure it doesn't get published to a remote repository.

      // .gitignore 
  .env
    

Make an API Call with a Secret Key

Now you can easily reference the key added to your .env file in you <App/> component without explicitly adding it to your code.

      import React,{useState, useEffect } from 'react';


const API_KEY = process.env.REACT_APP_API_KEY  
const API_URL = https://newsapi.org/v2/everything?q=usa&apiKey=${API_KEY}

function App(){
    const [newsList, setNewsList] = useState([]);
    useEffect(() => {
            getNews();
 }, []);
   const getNews = () => {
      fetch(API_URL)
          .then(response => response.json())    
          .then(data => setNewsList([...data]);
}
 
return (
   <div>
    { newsList.map( item => <p key={Math.random()}>{item.headline.title}</p> )}
  </div>
)
;}
    

You can also access secret keys set in your .env file in public/index.html. For example:

      <title>%REACT_APP_API_KEY%</title>
    

Now if you should push this code to your Github repository or any other remote repository, the keys in your .env file would not be pushed to the repository. That's way better!

Conclusion

In this guide you have learned how to protect your secret keys with create-react-app. Doing this is very critical for your app because a little oversight can compromise your app. That's all for now. Stay Safe! You can reach me on Twitter @DesmondNyamador.

Desmond Nyamador

Desmond N.

Desmond is a FullStack engineer, based in Ghana, West Africa. He enjoys teaching and upskilling software engineers and seeing the process of growth of individuals from beginner developers to masters in their fields.

More about this author