How to Stop Leaking OpenAI, Anthropic, and Stripe Keys in AI-Generated Frontends
The NEXT_PUBLIC_ trap, secret scanning, and how to safely proxy sensitive AI and payment tokens.
Table of Contents6 sections
One of the most terrifying notifications a founder can receive is an email from OpenAI or AWS with the subject line: "Your API key was detected in a public repository or client bundle."
Within minutes, automated crypto miners or LLM scraper networks can drain your card balance, racking up thousands of dollars in unauthorized usage.
When developing with AI tools like Cursor, Bolt.new, or v0, developers often ask the model: "Connect this button to OpenAI to generate copy" or "Create a checkout session with Stripe."
Because the AI wants to give you working code immediately, it frequently writes client-side code that directly imports secret environment variables or instructs you to put NEXT_PUBLIC_OPENAI_API_KEY in your .env file.
The NEXT_PUBLIC_ and VITE_ Prefix Trap
Frameworks like Next.js, Vite, and Remix have a strict convention:
- In Next.js: Variables starting with
NEXT_PUBLIC_are injected directly into the compiled JavaScript bundle sent to every visitor's browser. - In Vite / Bolt: Variables starting with
VITE_are bundled into the public client assets. - Without prefix: In Next.js, variables without
NEXT_PUBLIC_are only available in Node.js server environments.
When an AI model is asked to debug an error where process.env.OPENAI_API_KEY is undefined inside a React component, its quickest suggestion is often:
"Change your variable to NEXT_PUBLIC_OPENAI_API_KEY so the frontend component can read it!"
The moment you follow that advice, your private key is baked into public JS files:
// DANGEROUS CLIENT COMPONENT (Do NOT do this)
"use client";
import OpenAI from "openai";
export function CopyGenerator() {
// CRITICAL SECURITY LEAK: Anyone inspecting client network calls or JS bundle
// can view this secret key and use it on their own servers.
const openai = new OpenAI({
apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY,
dangerouslyAllowBrowser: true, // Notice the terrifying library warning!
});
// ...
}If a library forces you to pass a flag named dangerouslyAllowBrowser: true, it is actively telling you that your architecture has a fatal flaw.
How Bots Steal Keys in 60 Seconds
Automated bot networks constantly monitor GitHub commits and scan top Product Hunt launches:
- GitHub Scraping: If you push a
.envfile or hardcode a string matchingsk-proj-...orsk_live_..., GitHub Secret Scanning might notify you, but bots usually harvest the key before GitHub's alert finishes sending. - Web Bundle Crawling: Scrapers crawl JavaScript chunks (e.g.
/_next/static/chunks/app-...) using regex expressions looking for: sk-[a-zA-Z0-9]{32,}(OpenAI / Anthropic)sk_live_[a-zA-Z0-9]{24,}(Stripe Secret Key)ghp_[a-zA-Z0-9]{36}(GitHub Personal Access Token)postgres://...(Database Connection Strings)
The Correct Architecture: Server Proxies
Frontend components should never talk directly to third-party secret APIs. Instead, the frontend calls your own server, and your server communicates with the API using protected server-only credentials.
1. Keep the Key Server-Only
In your .env.local:
# NO "NEXT_PUBLIC_" prefix!
OPENAI_API_KEY="sk-proj-..."
STRIPE_SECRET_KEY="sk_live_..."2. Create a Protected Next.js Route Handler
// app/api/generate/route.ts
import { NextResponse } from "next/server";
import OpenAI from "openai";
import { auth } from "@/server/auth";
import { headers } from "next/headers";
import "server-only";
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY, // Safe on server
});
export async function POST(req: Request) {
// 1. Enforce authentication
const session = await auth.api.getSession({ headers: await headers() });
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// 2. Parse request body
const { prompt } = await req.json();
if (!prompt || typeof prompt !== "string" || prompt.length > 500) {
return NextResponse.json({ error: "Invalid prompt length" }, { status: 400 });
}
// 3. Make server-to-server call
const response = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: prompt }],
});
return NextResponse.json({ text: response.choices[0].message.content });
}3. Client Component Calls Your Internal Route
// app/components/generator.tsx
"use client";
export function CopyGenerator() {
async function handleGenerate(prompt: string) {
const res = await fetch("/api/generate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt }),
});
const data = await res.json();
console.log(data.text);
}
return <button onClick={() => handleGenerate("Summarize this doc")}>Generate</button>;
}Now, the client never sees the OpenAI key. They only see your internal endpoint, which you can rate-limit, authenticate, and monitor.
How to Check Your Live App Right Now
Run this quick test on your deployed website:
- Open your live app in Chrome.
- Open DevTools (
F12orCmd + Option + I). - Press
Cmd + Option + F(Mac) orCtrl + Shift + F(Windows) to open the Search Across All Files panel. - Search for:
sk-sk_liveservice_roleSECRETDATABASE_URL
If any search result appears in a file located under _next/static/ or your bundle assets, revoke that key immediately in the provider's dashboard and replace it with a server-only proxy.
Pre-Commit Guardrails & Scanners
To prevent secrets from ever touching git, install gitleaks:
# Install gitleaks on Mac
brew install gitleaks
# Scan your entire git repo history for leaked secrets
gitleaks detect --verboseYou can also use vibesupport's free automated scanner to inspect your live URL or GitHub repository for leaked tokens and insecure environment variables before you launch.
Don't let a hidden bug derail your launch.
vibesupport scans your AI-built codebase or live website for exposed secrets, missing database RLS, and broken access controls—then pairs you with senior engineers to fix them directly in GitHub.