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?
The problem with frontend code is that everything is exposed. Even if you try to hide the API key, anyone determined enough can just open up the dev tools or intercept the requests to find it. So, it’s basically impossible to keep it secure in the front end alone.
The best way to handle this is to set up a super simple backend that acts as a middleman. Your frontend sends requests to the backend, and the backend sends them to the API using the key, then passes the response back. The frontend never touches the key, so it’s safe.
Also, check if the API provider lets you restrict the key to certain domains or IP addresses. That way, even if someone steals your key, it won’t work outside of your app. It’s not perfect, but it’s better than leaving it wide open!
@Cody
Yeah, this is exactly what I’m going for. I’m mostly wondering if there’s a good managed service out there without all the bells and whistles of a full-blown serverless environment that can still handle this “middleman” approach. I’ve been using AWS and Google Cloud for these things, but it’s such a drag when all I want to do is get started on the frontend.
a good managed service out there without all the bells and whistles of a full-blown serverless environment that can still handle this “middleman” approach.
Huh! Maybe I’ll create one. That’s not a bad idea for a SaaS app for, I dunno, a couple of bucks per month?
@Nova
Next.js has two components. One is front-end and another is backend. Of course you need a server to run it this way. You can serve pages rendered in the server just like PHP. You can also create API routes in this server. The advantage of Next.js is that you can do everything in the same repo, and deploying to Vercel is really easy.
Rylan said: @Avery
Yeah, you can use CORS for this—no need to mess with IP.
I’m not too familiar with the depths of CORS; I guess this would protect browser requests. But someone could write a CLI or server app that’d call the middleman API.