Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Desmond Nyamador

Hiding Secret Keys in Create-React-App

Desmond Nyamador

  • Jun 15, 2020
  • 5 Min read
  • 57,514 Views
  • Jun 15, 2020
  • 5 Min read
  • 57,514 Views
Web Development
Front End Web Development
Client-side Framework
React

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 [email protected] 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.

1npx create-react-app react-secret-keys 

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

1cd react-secret-keys
2yarn 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!

1const API_URL = "https://newsapi.org/v2/everything?q=usa&apiKey=
2OW09823D03ASE48F34RUNF83"; // <- API_KEY inlined in the url
3
4function App(){    
5     const [newsList, setNewsList] = useState([]);    
6    useEffect(() => {          
7      getNews(); 
8}, []);   
9const getNews = () => {      
10fetch(API_URL)          
11.then(response => response.json())              
12.then(data => setNewsList([...data])
13;} 
14return (  
15 <div>    
16      { newsList.map( item => <p key={Math.random()}>{item.headline.title}</p> )} 
17 </div>)
javascript

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:

1-react-secret-keys
2
3 -node_modules
4
5 - public 
6
7 - src 
8
9 - .env  ←Right here
10
11 - .gitignore
12
13 - package-lock.json
14
15 - 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.

1// .env
2REACT_APP_API_KEY = OW09823D03ASE48F34RUNF83
3API_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.

1  // .gitignore 
2  .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.

1import React,{useState, useEffect } from 'react';
2
3
4const API_KEY = process.env.REACT_APP_API_KEY  
5const API_URL = https://newsapi.org/v2/everything?q=usa&apiKey=${API_KEY}
6
7function App(){
8    const [newsList, setNewsList] = useState([]);
9    useEffect(() => {
10            getNews();
11 }, []);
12   const getNews = () => {
13      fetch(API_URL)
14          .then(response => response.json())    
15          .then(data => setNewsList([...data]);
16}
17 
18return (
19   <div>
20    { newsList.map( item => <p key={Math.random()}>{item.headline.title}</p> )}
21  </div>
22)
23;}
jsx

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

1<title>%REACT_APP_API_KEY%</title>
html

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.