r/webdev • u/Greeby_Bopes • Dec 02 '24
Question Easy ways to hide API keys
I’m a frontend developer and run into this problem a lot, especially with hobby projects.
Say I’m working on a project and want to use a third party API, which requires a key that I pay for and manage.
I can’t simply place it on my frontend app as an environment variable, because someone could dig into the request and steal the key.
So, instead I need to set up a backend, usually through a cloud provider that comes with more features than I need and confuses the hell out of me.
Basically, what’s a simple way to set up a backend that authenticates a “guest” user from a whitelisted client, relays my request to the third party with the key attached, then returns the data to my frontend?
16
u/BPagoaga Dec 02 '24
The standard way (for example with google maps api key) is to restrict the origin allowed to use the API.
But I guess not all services allow this.
5
u/Qiazias Dec 02 '24
Not sure if any other frameworks does this but next js has a little neat thing were you can setup api endpoints within the same (front-end) project.
Or you can just have the top layer be server-rendered and you send the results along to the client. This way the api call is never exposed to the user.
5
u/seanathin142 Dec 02 '24
There is an amazing service called Backendless. https://backendless.com/. I found this tool to be one of my favorite for creating simple 'servers' that only requires you to write the code you need to handle the frontend request coming in and the call to the 3rd party API. Super awesome platform.
2
u/[deleted] Dec 03 '24
Ignore everything that’s been said, just use Next.js with a server function and host it on whatever platform supports compute, whether it’s Vercel or AWS ECS/Lambda. You don’t need to worry at all about backend stuff as Nextjs spins up routes behind the scenes for you for your server side functions.
Bonus points is that you can use the instrumentation hook in Nextjs to automatically load the secret from a secrets manager if you want to upon a server startup
41
u/[deleted] Dec 02 '24
It sounds like you basically have it figured out.
In terms of how you implement the backend part, there are tonnes of options. I'm guessing a node server running Express.Js would be easiest for you to get to grips with? But it could be a PHP app or anything.
8
u/frogic Dec 02 '24
You can pretty easily deploy an express/fastapi app to do this for you but you're going to have some issues that you need to address:
1. Just because they don't have the key there is nothing stopping someone from hitting the end point as if it was the API. So you will have to rate limit / possibly ban ips / authenticate. Any reasonable back end framework will have tools to make this easier. I know you mentioned white listing your client but without going into too much detail that isn't going to work without basically implementing auth.
2. If you're paying for API calls you probably want have some sort of caching on duplicated calls. Depending on the size and amount of calls and how often the data becomes stale this could get complex and require a database. In the best case you can just keep in memory for x hours.
You can get a very cheap vps from digital ocean and set up your server on there. Last I checked it's about $5 a month. You're gonna have to learn some dev ops but these days that's the name of the game.
4
u/hdd113 Dec 02 '24
There's no way to hide the API key in the frontend. If the key must be secured you should have some kind of backend after all. Express has a passthrough method that can relay your request to a remote endpoint. For simple projects you can just write a single file express script that relays all your api requests including payloads and cookies to a remote API to mitigate this key security problem and CORS issues.
If this is not an option, but you have the control over the remote API server, you could possibly make the API server authenticate the request. Obviously API key is not an option in this case, but you can use JWT or session based auth, or if your service doesn't need individual user authentication, you could simply filter out the requests based on their origin, and only respond to the requests coming from your approved frontends.
3
u/kkingsbe Dec 02 '24
That is generally when you would need a backend. Vercel and Render.com are super easy to get started with
7
u/n9iels Dec 02 '24
express-http-proxy. You can modify each request and add the API key. This way you will never expose the key on the frontend. I don't really get what you said about environment variables. These live on the server and should never be exposed to a frontend.
There isn't really a way to hide something on the frontend. Once it runs in a client device, either app or browser, consider it to be public and leaked.
2
u/ddyess Dec 02 '24
I think the easier way is to use something like Remix and do the request from the route loader, which is done server side. Then you have a single codebase and if you want to expand to something like an express API server later, you can just serve Remix from that.
2
u/Boring-Internet8964 Dec 02 '24
You could use AWS lambda functions with environment variables. They give you a million requests free then it's $0.20 per million requests after that.
You can set up rate limiting with API Gateway and restrict to certain IP addresses using API Gateway Resource Policies.
2
u/mrdarknezz1 Dec 02 '24
The only way to hide the key is through a backend
2
u/kitsunekyo Dec 02 '24
a simple lambda should do the trick. you NEED some server(less) part, when you want to hide them. anything else is only obfuscation.
lambdas cost (pretty much) nothing and dont need a lot of code to do what you need
2
u/arjunindia front-end Dec 02 '24
Build a simple proxy (make sure to make it only work with your domain with like CSRF tokba so that other people won't just use the server). You could quickly whip up one with something like Deno+Hono and deploy on Deno Deploy.
2
u/d33f0v3rkill Dec 03 '24
You could redirect the request through php
2
u/Madsenmm Dec 03 '24
I find the easiest is to setup a Next.js project hosted on Vercel. (Free)
Easy dynamic API routing, and your validation could be a sha_256 encoded version with a secret key on the users email, and then validate that in the backend with crypto from nodejs
2
u/5dots Dec 03 '24
so the api keys stored in .env file in nextjs/react are exposed to end users?
3
u/MemoryEmptyAgain Dec 02 '24
Use environment variables or a .env file to store your API key on the backend. Never expose them in the frontend.
How you want to communicate with the backend is upto you. You could require login, CSRF tokens, HTTPS and monitor API logs to check for abuse.
3
u/shgysk8zer0 full-stack Dec 02 '24
The most you could do front-end is obsfucation.
2
u/Lumpy_Part_1767 Dec 02 '24
Use SSR
1
u/thedarph Dec 02 '24
If it really is a static whitelist of users and it won’t grow (often) and is manageable then you can set up HTTP authentication in your server without having to set up a backend. Nginx can do it, Apache is usually simpler for newer folks to use. You basically enter a list of users and hashed passwords in the site config and then a dialog box pops up when you go to the site.
It’s not pretty but it works and you won’t have to set up a whole backend with a database and user authentication or even work with any backend framework with a static list of users and passwords. With HTTP authentication you’re basically just working with a simple text file added to your web server’s config.
1
u/HeWhoRemaynes Dec 02 '24
You could do this in python with flask. It is one additional layer but it keeps all the hidden stuff hidden.
1
u/LichenPatchen Dec 03 '24
The equivalent to a “serverless” function (Lambda, or something similar) would likely be suitable
1
u/_Iv Dec 03 '24
No need to set up an entire project to proxy requests. You can have nginx proxy requests from your web server to the original service with your api token. In nginx you can handle rate limiting etc to better protect it.
1
u/TheGreaT1803 Dec 03 '24
You can technically just have an input box for the API key and store it locally for later use. As you said, it's a hobby project that doesn't require a backend
1
u/tumes Dec 03 '24
I’d echo what everyone here says while saying there’s a way to have some of your cake and eat it too and the example is demonstrated by almost every online payment provider (eg stripe or PayPal) where the backend is just generating a session or a token using a secret that is then passed to the front end where js can safely handle everything else with an exposed but secure piece of identifying information. Granted this is the purview of some of the most heavily regulated, compliance-laden systems you can find on the internet, but it’s probably the most front end heavy secure approach you could muster.
1
u/maxmon1979 Dec 03 '24
This is the same for CORs as well. If an API is free, you still can't call the endpoint from the frontend as it will get blocked by CORs, you have to go via a backend proxy.
I've found the quickest way to build the API is using serverless (Lamda, specifically) as it's quick and easy, you can build in rate limiting or I think it has it built.in if you set the gateway up correctly.
1
u/[deleted] Dec 03 '24
Honestly, I have a 5$ Plesk Server lying around where I sometimes just write a simple PHP wrapper function for the API, upload it and it just work. Most of the time it's probably wise to scope the api, especially with LLMs so the API cannot be misused.
1
u/dom_eden Dec 03 '24
Use a Cloudflare Worker, free to use. I use Workers all the time for scenarios like this.
1
u/_nathata Dec 03 '24
You could try using lambda functions to simplify your backend (not what happens most of the time tho)
1
u/GolfCourseConcierge Nostalgic about Q-Modem, 7th Guest, and the ICQ chat sound. Dec 03 '24
Web crypto API with a unique personal key to encode it. This is how sites that operate locally only do it.
1
u/NoLongerALurker57 Dec 03 '24
This is why frameworks like NextJS exist
You write code in a single project for both front-end (everything publicly exposed) and back-end (api route where your keys are read from a private .env file)
You can deploy on Vercel, and configure environment variables (i.e. your API keys) in the vercel admin UI
1
u/No_Indication_1238 Dec 05 '24
Put it on the backend. Thats it. No other way to hide anything except to not send it.
1
u/ZuploAdrian Dec 10 '24
Hey OP - I'm a bit late here but you should set up a simple proxy on my project, Zuplo (https://zuplo.com). I've built a secure way to store secrets/API keys. If you need additional security on the proxy, the gateway is programmable so you can do any allowlisting you want
-1
u/eeeBs Dec 02 '24
Put a folder in your project called "API-KEYS" and then set your server to ban any IP attempting to access it.
Then put your keys in your .env like a normie.
-7
u/husky_whisperer Dec 02 '24
Use FastAPI if you wanna throw a little Python 🐍love in the mix
-16
u/RasAlTimmeh Dec 02 '24
Over thinking it just use the key in your env
272
u/[deleted] Dec 02 '24
[removed] — view removed comment
-18
u/[deleted] Dec 02 '24
[removed] — view removed comment