How to Hide API Key and remove console errors in Axios

Irfani Silviana
4 min readMar 4, 2021
A phone with lock photo on the screen
Photo by Franck on Unsplash

I’m currently taking a React course on SheCodes and working on a project to build A Weather App using React. You can find the repo here https://github.com/irSilviana/weather-react

While I coded, I made a small mistake and it called the API more than the maximum allowance number. Later, I fixed that issue. But then, I got this email from OpenWeatherMap.

Email of OpenWeatherMap API usage alert
Email of OpenWeatherMap API usage alert

Fortunately, I’m using a free account, and after 1-hour I was able to use the same API key.

I think it’s important to pay attention to security since the beginning. There are so many stories that cause developer/app owner to fatal financial consequences simply by exposing the API key in their open-source code, mainly through GitHub.

However, because of this problem, I paid more attention to 3 things:

  1. How axios handle the API key and not exposing the API key to users via the developer console?
  2. How to stop axios from displaying the 404 error in the console.log?
  3. I’ve uploaded my code into GitHub and exposed my API key in the code, how to fix this mistake?

So what am I trying to do is to build a weather app using Create-React-App. The steps are:

  1. Generate a weather API from OpenWeather
  2. Fetch weather data from the API using Axios
  3. Display the weather data on the Weather App
  4. Hosting the app on Netlify

At first in the Search.js, inside the Search component, a part of my code was:

function searchByCity() {
let apiKey = `123apihereis4p1k3yppiii`;
let unit = “metric”;
let apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=${unit}`;
axios.get(apiUrl).then(showTemperature);
}

And to answer all those 3 questions, here is what I did.

Front End: Hide API Key (React)

1. Create a file called .env in the root of your project's directory

It looks like this:

- your_project_folder
- node_modules
- public
- src
- .env <-- create it here
- .gitignore
- package-lock.json
- package.json

2. Inside the .env file, prepend REACT_APP_ API_KEY name of choice and assign it

The create-react-app tool uses REACT_APP_ to identify these variables. If you don't start your API key name with it, create-react-app won't see it.

// .envREACT_APP_WEATHER_API_KEY=your_api_key  <-- correct
API_KEY=your_api_key <-- wrong
// Example
REACT_APP_WEATHER_API_KEY=123456

3. Add the .env file to your .gitignore file

After you add the line below, save the .gitignore file and do a git status to make sure your .env file does not appear as a new file in git.

// .gitignore# api keys
.env <-- add this line
# dependencies
/node_modules
...

4. Access the API key via the process.env object

To check that you can access your API key, go to your App.js file and add a console.log at the top below the require statements. After saving the file and reloading the page, if the console log does not show your API key, try restarting the react server.

I stopped the server (Control + C) and restarted the server npm start. Be sure to remove the console log line before committing your code.

// src/App.jsimport React, { Component } from 'react';
import './App.css';
console.log(process.env.REACT_APP_WEATHER_API_KEY) <-- remember to remove this class App extends Component {
...

So at this point, I was using a new API Key for step #2, and I deleted the first API Key that I got from theOpenWeatherMap.

Delete the default (first) API Key

5. Update the function in the Search component inside Search.js

This approach works to remove the console errors from Axios that return 404 error in the console.log.

When axios return 404 error, it shows your apiUrl including your API Key in the developer console. This solution has a security flaw: the API key is exposed to users.

That’s why it’s better to add the code with .catch(error)=> & console.clear()

function searchByCity() {const apiKey = process.env.REACT_APP_WEATHER_API_KEY;
let unit = "metric";
let apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=${unit}`;
axios.get(apiUrl).then(showTemperature).catch((error) => {if (error.response && error.response.status === 404) {console.clear();alert("🌏 Please type the correct city name");}});}

For more complete information about axios handling errors, please read this section axios/axios: Promise based HTTP client for the browser and node.js (github.com)

Deployment: Hiding API Keys on Netlify

Then from your Netlify account, go to the selected Site. Under Site overview tab click Site Settings > Build & deploy > Environment > Environment variables. There, add your variable for the API Key, just like you had in your .envfile and click Save.

Add API Key to Netlify

This approach has helped me to solve the problems. Let me know about your comment and if you have a suggestion for a better approach.

Please check my repository on GitHub to get a fully functional weather app. Stay safe! 🤓👩‍💻

--

--