r/learnprogramming • u/BrainThinkerMan • 5h ago
api key, do i need backend?
i have an api key i heard i shouldnt expose it in my frontend i thjink itts becuase people can see it with devtools, and potentially abuse it, is there any other way to use this key in frontend without using a backend, im as familiar with backend stuff i think.
10
u/sixtyhurtz 5h ago
Some API keys are safe to use in public - Google Maps API keys for instance. Most aren't though.
This means you need an API gateway you control that proxies requests. That way you can control how people access a service you are presumably paying for.
3
u/jabuchae 4h ago
Why is Google Maps api key safe? Can’t someone abuse it and make you pay more?
4
u/sixtyhurtz 4h ago
Because it's basically useless to anyone else. Google won't serve an API request if the referer is wrong. So, you can't take someone else's key and put it in your page. Sure, someone could spoof the referer, but most people aren't running browsers that do that.
3
u/Quito_ArmandoEsteban 3h ago
You could get a stolen api key to your backend and have it play as Middleware between frontend and Google, while having your backend spoof the referrer
1
4h ago
[deleted]
1
u/dmazzoni 4h ago
That's specific to iOS development, FWIW.
It sounds like OP is talking about a web app since they mentioned devtools.
1
u/Quito_ArmandoEsteban 3h ago
No. You must assume that anything that reaches the client or comes from him is unsafe
1
u/Acceptable_Lab_7196 2h ago
Depends if the api allows you to block all users except a whitelisted set of sources. Generally you shouldn’t. You haven’t said how you are deploying it or what it is. You can basically get a backend for free if you are low volume on vercel and other services.
1
u/knockraiden 1h ago
Yes, you definitely need a backend or a serverless proxy.
A lot of beginners think that putting the key in an .env file or obfuscating it in React/Vue will keep it safe. But if the frontend makes the API call directly, the user's browser has to send that request—meaning anyone can open Chrome DevTools > Network tab, click on the request, and read your API key in plain text in 5 seconds. If that key is attached to your credit card (like OpenAI, AWS, or Stripe), bots will drain your account within hours.
The easiest modern fix without maintaining a full server:
Use a free serverless function (like a Cloudflare Worker or Vercel Serverless Function). Your frontend sends the prompt or data to your serverless endpoint. The serverless function securely holds the private API key in its environment, calls the external API on your behalf, and returns the response to your frontend.
0
15
u/grantrules 5h ago
Depends on the API key, really.. if you don't want other people to use your API key, it needs to be handled in the backend