๐ช๐ต๐ ๐ ๐ฆ๐๐ผ๐ฝ๐ฝ๐ฒ๐ฑ ๐๐ฎ๐ฟ๐ฑ๐ฐ๐ผ๐ฑ๐ถ๐ป๐ด ๐๐ ๐๐ฃ๐ ๐๐ฒ๐๐ ๐ถ๐ป ๐ ๐ ๐๐ฟ๐ผ๐ป๐๐ฒ๐ป๐ฑ
I once pushed a commit that exposed my OpenAI API key in a JavaScript bundle.
I caught it before anyone else saw it. The panic felt real. I knew better, but I was in a hurry. I told myself I would fix it later. Later never came until a code review flagged the error.
That mistake taught me a lesson about security.
Many developers try to hide API keys using .env files in frontend builds. This is a mistake. Build tools inject those keys into your JavaScript code as plain text. Anyone can open DevTools and find your key.
I tried different ways to fix this:
โข Express servers: These work but require you to manage servers, CORS, and scaling. It felt like too much work for a small project. โข Cloud functions: AWS Lambda or Google Cloud functions felt too heavy for a single endpoint.
I found a better way using serverless functions on platforms like Netlify, Vercel, or Cloudflare Workers.
The strategy is simple:
- Write a small function that stays on the server.
- The function holds your API key in a real environment variable.
- Your frontend calls your function instead of the AI service.
- Your function adds the key and forwards the request to the AI.
This pattern is called Backend For Frontend (BFF). It keeps your secrets safe without the cost of a full server.
Things to watch out for:
โข Cold starts: Functions may take a moment to wake up. โข Timeouts: AI responses can take longer than the default 10-second limit. โข Complexity: You may need a router if you want to use different request methods.
Stop relying on client-side environment variables for secrets. Use a serverless proxy to keep your keys private.
How do you handle API keys in your frontend apps? Do you use serverless proxies or a dedicated gateway?
Source: https://dev.to/__c1b9e06dc90a7e0a676b/why-i-stopped-hardcoding-ai-api-keys-in-my-frontend-2dkd