Security10 min read

How to Prevent API Key Exposure in Vibe-Coded Next.js Apps

Vibe-coded Next.js apps routinely ship API keys in browser bundles. Learn to detect NEXT_PUBLIC_ leaks, scrub git history, and block secret exposure.

API key exposure is the most prevalent and most immediately costly security failure in vibe-coded Next.js applications. A leaked OpenAI key gets used for someone else's inference bill within minutes of exposure. A leaked Stripe key enables refund fraud or card testing. A leaked Supabase service role key gives complete, unrestricted access to every row in every table in your database — bypassing every Row-Level Security policy you wrote. The surprising part is not that this happens; it is how reliably AI coding tools create the conditions for it.

The root cause is structural. Tools like Lovable, Bolt, Cursor, and v0 generate code that works in the development sandbox they were tested in — and in that sandbox, the fastest path to a working API call is often to pass the key directly. That approach produces functioning demos. It fails in production because it ships the secret to every visitor's browser. Escape.tech's 2026 scan of 1,764 production vibe-coded apps found 453 with critical vulnerabilities; a substantial share were secret exposure issues. The broader vibe-coding security risk landscape is documented in depth — this post focuses specifically on how API keys leave the server, how to find them once they have, and how to build the architecture that keeps them server-side.

This guide covers Next.js specifically because it is the dominant framework for vibe-coded apps in 2026, and because its environment variable system has a specific behavior — the NEXT_PUBLIC_ prefix — that is responsible for most browser bundle leaks. The same principles apply to any framework that distinguishes server-side from client-side environments, but the Next.js specifics are where most real-world leaks originate.

How NEXT_PUBLIC_ Ships Your Secrets to Every Browser

Next.js manages environment variables in two namespaces. Variables without the NEXT_PUBLIC_ prefix are available only during the build process and in server-side code — API routes, Server Actions, getServerSideProps, and middleware. They are never sent to the browser. Variables with the NEXT_PUBLIC_ prefix are inlined into the JavaScript bundle at build time. The literal string value of the variable — including the full API key — is substituted into every file that references it and compiled into the static assets served to your users.

  • →Build-time inlining means the secret is baked into the bundle. It is not fetched from a server at runtime. It is not stored in a cookie. It is literally written into the JavaScript files that live in your CDN. Anyone who downloads your app downloads the key.
  • →process.env.NEXT_PUBLIC_OPENAI_API_KEY in your client component becomes the string sk-proj-... in the compiled output. You can find it with View Source or by searching the .next/static/chunks directory for the key prefix.
  • →AI tools suggest NEXT_PUBLIC_ because it makes the demo work. When Cursor or v0 generates a component that calls the OpenAI API directly from the browser, it uses NEXT_PUBLIC_ to pass the key because that is the only way to make it accessible in a client component. The code runs. The demo works. The key is now public.
  • →The fix is not to rename the variable. It is to move the API call to the server. No variable prefix makes a secret safe on the client — NEXT_PUBLIC_ does not mean safe to share; it means will be included in the browser bundle by design.
  • →Even in development, treat NEXT_PUBLIC_ variables as public. If your .env.local is listed in .gitignore but your .env.example has NEXT_PUBLIC_OPENAI_API_KEY=sk-proj-..., you have documented where the production key goes in your repository.

Four Ways Vibe-Coded Apps Leak API Keys

Secret exposure in vibe-coded apps follows a small number of patterns. Understanding which pattern caused your leak determines whether rotation alone is sufficient or whether you also need to scrub history.

  • →NEXT_PUBLIC_ prefix in client components. This is the most common pattern. The key is in the browser bundle of every deployed version. Anyone who visits the app can find it. Rotation fixes the exposure, but every old deployment still contains the old key until it is taken down or the bundle is replaced.
  • →Direct API calls from client-side fetch with keys in headers. Some AI-generated code calls external APIs from useEffect or event handlers, passing the key as an Authorization header in a fetch call. The key is visible in the browser's Network tab on the first request. This is the same exposure as NEXT_PUBLIC_ — the key is in the JavaScript source — but it is easier to miss in a source scan because the key is in a string rather than a substituted variable.
  • →.env files committed to git. AI tools occasionally suggest committing .env.local or .env to the repository for easy setup. Even when you delete the file in a later commit, the key remains in git history at every commit before the deletion. GitHub Secret Scanning will detect and alert on this. If the repository is or was ever public, assume the key was indexed by scanners and must be rotated.
  • →Source maps exposing minified bundles. Next.js generates source maps for production builds to assist debugging. When source maps are enabled and deployed alongside the bundle, they provide a human-readable reconstruction of your code — including the values of inlined NEXT_PUBLIC_ variables — to anyone who downloads them. Disable production source maps with productionBrowserSourceMaps: false in next.config.js, or serve them from an authenticated endpoint only.

How to Scan Your Production Build for Exposed Keys

Before fixing anything, audit the current state. If keys are already in a deployed bundle, they need to be rotated — not just removed from code. The audit tells you which keys are affected and therefore which credentials to invalidate.

  • →Build the production bundle locally: run npm run build to generate the .next directory. This contains the same JavaScript files your users download.
  • →Search the static output for key prefixes. OpenAI keys start with sk-proj- or sk-. Stripe publishable keys start with pk_live_ or pk_test_. Stripe secret keys start with sk_live_ or sk_test_. Supabase service role JWTs are base64 and long — look for eyJ in the bundle. Anthropic keys start with sk-ant-. Run a recursive text search across .next/static/chunks for each prefix.
  • →Check the Network tab in browser DevTools. Load your production app with DevTools open and examine the Sources panel. Search for sk- or the first few characters of a known key. The browser's JavaScript debugger has full access to the bundle — the same access an attacker has.
  • →Run npx deployready against your repository. DeployReady's secret scanning check looks for exposed API keys, service role credentials, and common secret patterns in both the codebase and the build output. It reports found secrets with severity ratings and shows the file and line where each was detected, so you can target rotation and remediation precisely.
  • →If the repository is on GitHub, check the Security tab for Secret Scanning alerts. GitHub automatically scans public repositories — and optionally private repositories on paid plans — for over 200 known secret formats and alerts when it finds one.

The Fix: Move Every External API Call to the Server

The only correct fix for NEXT_PUBLIC_ key exposure is architectural: every call that uses a secret must happen on the server. The API key never leaves your server environment. The browser calls your API route; your API route calls the external service. This is not a workaround — it is the intended Next.js pattern for external API calls, and it has the added benefit of letting you add authentication, rate limiting, and input validation to every external request. Our security audit service typically finds this pattern implemented incorrectly in a majority of vibe-coded apps we review — not because developers missed it, but because AI tools default to the client-side path.

  • →Create a Next.js Route Handler for each external API call. A file at app/api/generate/route.ts can call the OpenAI API using process.env.OPENAI_API_KEY with no NEXT_PUBLIC_ prefix and return the result. The browser POSTs to /api/generate. The key never reaches the browser.
  • →Server Actions are an alternative for form submissions and mutations. A Server Action marked with use server runs only on the server. It can read environment variables safely and call external APIs without exposing credentials to the client.
  • →For Supabase, the anon key is designed to be public — it is the key that client-side Supabase SDK calls use, and your Row-Level Security policies are what protect data access. What must never reach the browser is the service role key (SUPABASE_SERVICE_ROLE_KEY without NEXT_PUBLIC_), which bypasses RLS entirely. If you see NEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEY anywhere, that is a critical exposure — rotate it immediately.
  • →Remove NEXT_PUBLIC_ from every variable that holds a secret. Environment variables for external service credentials, database connection strings, signing secrets, and API keys should never carry the NEXT_PUBLIC_ prefix. If code that uses them is in a client component, move the call to a Route Handler or Server Action.
  • →After moving secrets server-side, re-run the build and repeat the audit steps above. Confirm the .next/static output no longer contains the key prefixes you found in the initial scan.

Scrubbing Exposed Keys from Git History

If a key was committed to a git repository, removing it from the latest commit is not enough. The key still exists at every historical commit before the removal. For public repositories, the key was likely indexed by scanners within seconds of being pushed. The correct response is always rotation first, then history rewrite.

  • →Rotate the key immediately. Before doing anything else, generate a new key at the provider's dashboard and update your production environment variable. The old key should be revoked at the provider — deleted, not just cycled. Only after the old key is revoked does the history rewrite have value. A key in history is dangerous while it is valid; rotation is what stops the bleeding.
  • →Use git-filter-repo to rewrite history. git-filter-repo is the recommended tool for removing secrets from git history. It rewrites every commit that contains the target string, replacing it with a placeholder. This produces a new repository history that is incompatible with the old one — all collaborators will need to re-clone or rebase.
  • →BFG Repo Cleaner is an alternative that is simpler for single-file cleanups. It operates on files rather than diffs and can be faster for large repositories with binary files, though git-filter-repo handles more edge cases correctly.
  • →Force-push the rewritten history and require all collaborators to re-clone. A history rewrite changes commit SHAs from the first affected commit forward. Any branch that has not been rebased onto the new history will re-introduce the old commits if merged. All team members must re-clone from the rewritten remote.
  • →GitHub retains cached views of deleted content briefly. After a force-push, cached views of the old repository state may persist. GitHub support can clear these for public repositories if you submit a request on security grounds. For private repositories, rotating the credential remains the essential step.

Preventing Future Leaks: Pre-Commit Hooks and CI Gates

One-time remediation is not enough. Vibe-coded apps are frequently iterated on rapidly, and new API calls — with new keys — are added regularly. The only way to prevent recurring exposure is to build automated checks into the development workflow. Adding DeployReady as a CI security gate catches secret exposure and many other security issues on every push before it reaches production.

  • →Add a git pre-commit hook with git-secrets or detect-secrets. These tools scan staged files for known secret patterns before each commit, refusing the commit if a match is found. They need to be configured with the patterns for the APIs your project uses — a default configuration catches generic patterns but misses app-specific credentials.
  • →Add .env, .env.local, .env.production, and similar files to .gitignore at project creation. This prevents accidental commits of local secret files. Commit a .env.example with placeholder values to document the required variables without exposing real values.
  • →Run npx deployready in your CI pipeline on every pull request. DeployReady scans for exposed secrets, missing security headers, and common auth bypass patterns as a lightweight CI check. When it finds a NEXT_PUBLIC_ variable that looks like a credential, it fails the check with a description of the finding — the PR cannot be merged until the issue is addressed.
  • →Enable GitHub Secret Scanning for your repository. For public repositories it is automatic. For private repositories on GitHub Enterprise, it can be configured under repository security settings. The push protection feature available on GitHub Advanced Security blocks pushes that contain known secret formats before they reach the remote.
  • →Establish a rotation practice for all production secrets on a regular cycle, independent of incidents. Rotating API keys quarterly ensures that any key that did leak and was not noticed becomes invalid within a predictable window.

Supabase Keys: Which Ones Are Safe Client-Side

Supabase is the backend of choice for a large share of vibe-coded apps, so its key model deserves specific attention. Supabase projects have two keys that look similar but have entirely different permission levels. Getting this distinction wrong is one of the most common critical vulnerabilities in AI-built apps, and the Supabase RLS security guide covers the access control side in depth — here is the key-safety dimension.

  • →The anon key (NEXT_PUBLIC_SUPABASE_ANON_KEY) is designed to be public. It is used by the Supabase client SDK running in the browser. Access to data is controlled by your Row-Level Security policies, not by keeping the anon key secret. The key itself grants no data access beyond what RLS allows. It is safe to include in your Next.js build with the NEXT_PUBLIC_ prefix — this is the intended usage.
  • →The service role key (SUPABASE_SERVICE_ROLE_KEY) bypasses all Row-Level Security and has full read/write access to every table, function, and storage bucket in your project. It must never carry the NEXT_PUBLIC_ prefix, never appear in client-side code, and never be committed to git. If you see NEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEY in any codebase, treat it as a critical incident: rotate the key and audit what was accessed.
  • →AI coding tools sometimes generate server-side operations that use the service role key correctly, then a developer moves that code to a client component for convenience, changing the import and adding NEXT_PUBLIC_ to make it compile. That migration is the most common path to service role key exposure in Supabase apps.
  • →The URL (NEXT_PUBLIC_SUPABASE_URL) is also designed to be public. Knowing your Supabase project URL does not grant any access — the anon key and service role key are the gatekeepers.

Frequently Asked Questions

If I delete an API key from my code and push the change, is the key safe?

No. The key still exists in every git commit before the deletion and in every bundle that was deployed while the key was present. Anyone who cloned the repository before the deletion, or who visited the app while the old bundle was live, may have already captured the key. The correct response is to rotate the key at the provider first, then scrub the history. Rotation invalidates the exposed credential regardless of whether anyone captured it.

Does using an .env.local file prevent API key exposure in Next.js?

.env.local prevents the key from being committed to git, provided it is listed in .gitignore. It does not prevent browser bundle exposure. If your code reads an environment variable with a NEXT_PUBLIC_ prefix, Next.js inlines the value from .env.local into the browser bundle at build time regardless of where the value comes from. The .env.local file is a development convenience, not a security boundary.

Which AI coding tools most commonly generate code with exposed API keys?

Bolt, Cursor, and v0 are the most commonly cited generators of direct client-side API calls with NEXT_PUBLIC_ keys. Lovable routes external API calls through Supabase Edge Functions by default, which keeps secrets server-side — a deliberately safer default. However, any AI tool can produce unsafe patterns when prompted to make an API call work directly in a component, or when a developer moves server-side code to a client component for debugging. The tool matters less than the architectural principle: secrets belong on the server.

How quickly are exposed API keys discovered and exploited?

Very quickly. Automated scanners monitor GitHub for secret patterns in real time. Developer accounts on Reddit and Indie Hackers report keys being exploited within minutes of a public push. The vectors vary: some attackers mine keys for LLM inference credits, others test them against Stripe for card-testing fraud, others use them for spam infrastructure. Assume an exposed key was used. Rotate it and audit the provider's usage logs for the period of exposure.

Should I add spending limits as a backup defense against leaked API keys?

Yes, but not as a substitute for fixing the exposure. Spending limits and usage alerts at OpenAI, Anthropic, and other providers will notify you when unusual usage occurs and limit the financial damage. They do not prevent the key from being used for data access, account manipulation, or activities that do not register as spend. Set hard spending caps and email alerts on every provider account, then treat them as an incident-detection layer, not a primary defense.

How Belsoft Helps with Vibe-Coded App Security

Secret exposure is usually one of several security issues in a vibe-coded app that ships quickly. The same codebase that has a NEXT_PUBLIC_ key often has a Supabase service role key in a client component, missing authentication on API routes, and RLS disabled on one or more tables. These vulnerabilities do not announce themselves — a working app in development gives no indication that secrets are leaking until the first attacker finds them. Running DeployReady gives you an automated baseline scan in seconds: exposed secrets, missing security headers, unauthenticated endpoints, and common auth bypass patterns. Run it before you launch and after every significant change.

For a full security review before an enterprise deal, a SOC 2 audit, or after an incident, Belsoft's security audit service goes deeper: manual review of authentication flows, data access authorization, API route protection, and AI feature security by engineers who know how these apps are built and where they break. We test the patterns that automated tools miss — business logic assumptions, tenant isolation failures, and permission escalation paths — and return a prioritized fix list with enough detail that your team can implement it. For teams that want support through the fix cycle, we offer retest support as part of the engagement.

“An API key in your browser bundle is not a misconfiguration you can patch. It is a credential that every visitor downloaded. Rotate it, then fix the architecture.”

Written by

Marco Silva

Security Engineer, Belsoft Solutions

Ready to partner?

Let's talk about your company.

30 minutes. No pitch. We talk through how you run today and where AI and automation would help.

Book a free audit
logo

Your AI & automation transformation partner: we audit, build, and train your team, then stay embedded as you grow.

Member ofNVIDIA Inception Program

Copyright Ⓒ 2026 BelSoft. All Rights Reserved.

BELSOFT, LDA · NIPC 517893258 · Lisbon, Portugal