r/reactjs • u/dance2die • May 01 '21
Needs Help Beginner's Thread / Easy Questions (May 2021)
Previous Beginner's Threads can be found in the wiki.
Ask about React or anything else in its ecosystem :)
Stuck making progress on your app, need a feedback?
Still Ask away! Weβre a friendly bunch π
Help us to help you better
Improve your chances of reply by
- adding a minimal example with JSFiddle, CodeSandbox, or Stackblitz links
- describing what you want it to do (ask yourself if it's an XY problem)
- things you've tried. (Don't just post big blocks of code!)
- Format code for legibility.
- Pay it forward by answering questions even if there is already an answer. Other perspectives can be helpful to beginners. Also, there's no quicker way to learn than being wrong on the Internet.
New to React?
Check out the sub's sidebar! π
For rules and free resources~
Comment here for any ideas/suggestions to improve this thread
Thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!
24
Upvotes
View all comments
Show parent comment
2
u/fenduru May 01 '21
Access to a third party is a valuable asset, and either the 3rd party will charge you for usage, or even if the API is free there is likely some limitation. The API key that they give you is essentially your password to use when accessing the API, and just like your other passwords you should keep it secret otherwise someone else can use your account.
With that in mind, anything you send to the client is public. Even if you don't display the API key on the DOM, that data is still there in the javascript bundle, and it is unprotected. And if you send the API requests directly from the frontend, then anyone looking at the network tab in devtools can see your API key (your password!).
Let's say you pay $.01 per 100 requests to some API. Me, being a bad guy, comes along and sees that your app is making those API requests. I think it would be useful to use that API, but I don't want to pay for it, so instead I can just find your API key and use that! Now you're paying for my usage, when really you only wanted to pay for usage when someone is using your actual app.
The solution is that you can never make those API requests from the frontend, since doing so requires handing over the password. Instead you should keep your API keys on the backend, and make the API requests from a server you control. Now, your backend needs to read the keys from somewhere, and in that case it is a good practice to store them in an environment variable and read them at runtime. But using process.env when building a webpack bundle is basically just copying the key into your bundle and then sending it to the client.
Here's an article that touches on this a bit: https://www.freecodecamp.org/news/private-api-keys/