Keeping API key hidden using react

Keeping API key hidden using react
0
#1

Hey all,

I’ve got an API key that I’m obviously meant to keep private, that I want to use in a react app.
I’ve stored it as an environment variable in the react app by creating a .env file and adding
REACT_APP_APIKEY="[my api key]"

Now here is an example fetch to the api;

fetch(`http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&APPID=${process.env.REACT_APP_APIKEY}`)

I don’t have to write my apikey explicitly in the code here, so i can upload everything except the .env file to github and the apikey will still be private, but if I put a demo up that actually uses this code, you will be able to go to the network tab in chrome and see my api key whenever you make a request. I could host my own node.js api, which I send the fetch request to then forward the fetch to the actual api and inject the apikey there, but that seems like a pretty complicated solution. Any other ideas? or should I just not worry about it?

#2

Option 2: Don’t let the client side touch the API key:
https://www.rockyourcode.com/secret-keys-in-react

1 Like
#3

Okay, I’m pretty sure I get it. Just to clarify, in order to build a simple weather app that uses an API key, I will also need to write a backend, just because of the use of an API key ?

1 Like
#4

Yes, your react app can send an ajax request to the endpoint that you set up and your server can call the API

2 Likes
#5

Yeah, security can be annoying, but as you have said through your very question, you recognize that secrets must be kept between trusted parties, and the client isn’t one.

2 Likes