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

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.

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:

Here is how you set up a proxy using Netlify Functions:

  1. Create a file at netlify/functions/ai-proxy.js.
  2. Write a handler to receive the request.
  3. Use process.env.AI_API_KEY to grab your secret.
  4. Use fetch to send the request to the AI service.
  5. 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:

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