๐—ช๐—ต๐˜† ๐—œ ๐—ฆ๐˜๐—ผ๐—ฝ๐—ฝ๐—ฒ๐—ฑ ๐—›๐—ฎ๐—ฟ๐—ฑ๐—ฐ๐—ผ๐—ฑ๐—ถ๐—ป๐—ด ๐—”๐—œ ๐—”๐—ฃ๐—œ ๐—ž๐—ฒ๐˜†๐˜€ ๐—ถ๐—ป ๐— ๐˜† ๐—™๐—ฟ๐—ผ๐—ป๐˜๐—ฒ๐—ป๐—ฑ

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:

  1. Write a small function that stays on the server.
  2. The function holds your API key in a real environment variable.
  3. Your frontend calls your function instead of the AI service.
  4. 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