๐ช๐ต๐ ๐ ๐ฆ๐๐ผ๐ฝ๐ฝ๐ฒ๐ฑ ๐๐ฎ๐ฟ๐ฑ๐ฐ๐ผ๐ฑ๐ถ๐ป๐ด ๐๐ ๐๐ฃ๐ ๐๐ฒ๐๐ ๐ถ๐ป ๐ ๐ ๐๐ฟ๐ผ๐ป๐๐ฒ๐ป๐ฑ
I once pushed a commit that exposed my OpenAI API key in a JavaScript bundle.
I caught it early, but it was a wake-up call. I thought it was fine because it was a prototype. I was wrong.
Many developers use environment variables in frontend builds to hide keys. This is a mistake. Build tools inject those keys into your code as plain text. Anyone with DevTools can find them and use your credits.
I tried different solutions to fix this.
- An Express server on Heroku: Too much work to manage scaling and CORS.
- AWS Lambda or Google Cloud Functions: The setup felt too heavy for a small project.
The best solution was using serverless functions through Netlify or Vercel.
This follows the Backend For Frontend pattern. You write a small function that lives on the server. Your frontend calls your function, and your function calls the AI API.
How it works:
- Your API key stays in a server-side environment variable.
- The browser never sees the key.
- The user only sees your function URL.
Here is how you set up a proxy using Netlify Functions:
- Create a file at netlify/functions/ai-proxy.js.
- Write a handler to receive the request.
- Use process.env.AI_API_KEY to grab your secret.
- Use fetch to send the request to the AI service.
- Return the response to your frontend.
In your frontend code, you change your fetch call:
Instead of calling OpenAI directly, you call: const proxyUrl = "/.netlify/functions/ai-proxy";
Important things to remember:
- Cold starts: Serverless functions can take a moment to start.
- Timeouts: Free plans often have a 10-second limit. Long AI responses might hit this.
- Costs: Most platforms have large free tiers that suit personal projects.
Stop trusting client-side environment variables with your secrets. Use a serverless proxy to keep your keys safe.
How do you manage API keys in your apps? Do you use serverless proxies or an API gateway?
Source: https://dev.to/__c1b9e06dc90a7e0a676b/why-i-stopped-hardcoding-ai-api-keys-in-my-frontend-2dkd
Optional learning community: https://t.me/GyaanSetuAi