Why Exposed API Keys in Frontend Code Are Dangerous

Quick answer: Exposed API keys in frontend JavaScript are public secrets. Because browsers must download your code to run it, any key in your React or Vue bundle is visible to bots and attackers. This leads to account takeovers and massive financial bills. The fix: rotate keys immediately and move them to a server-side proxy.

By Paula C · Kraftwire Software

· 10 min read

Exposed API keys in frontend code are dangerous because they are publicly readable by any visitor, bot, or malicious actor. Every line of JavaScript shipped to a browser can be inspected; therefore, a "secret" key in your frontend is no longer a secret. Attackers use automated scanners to find these keys within seconds of deployment to steal data, hijack AI models, or run up unauthorized cloud costs.

Why Are API Keys in Frontend Code a Problem?

The fundamental architecture of the web is the primary reason why frontend API keys are a liability. When a user visits your website, their browser downloads your entire frontend bundle · including your JavaScript, CSS, and HTML. If you have hardcoded a secret key into your React, Vue, or Svelte components, you have effectively handed that key to the world.

This is particularly critical in the era of "vibe-coding" and AI-assisted development. Tools like Lovable, Bolt.new, and Cursor are excellent at generating functional code quickly, but they often prioritize "making it work" over security best practices. In SimplyScan's scans of AI-built apps, 30% had at least one HIGH or CRITICAL severity issue, often involving exposed credentials or broken authentication.

How Attackers Find Your Keys

It takes less than 30 seconds for a human to find an exposed key using browser DevTools (F12). By navigating to the "Sources" or "Network" tab and searching for strings like sk_, api_key, or bearer, anyone can extract your secrets.

However, the real threat comes from automated bots. Malicious actors run massive distributed crawlers that monitor the web and public GitHub repositories in real-time. In 2023 alone, GitHub detected over 10 million secrets exposed across more than 12 million public repositories. These bots are programmed to recognize specific patterns, such as:

  • OpenAI keys (sk- followed by alphanumeric characters)
  • Stripe secret keys (sk_live_)
  • AWS Access Key IDs (AKIA...)
  • Algolia Admin keys

A security discovery by researcher Ben Zimmermann found 39 Algolia Admin API keys exposed in the frontend JavaScript of major open-source documentation sites. These keys allowed full administrative access to the search indices, demonstrating that even high-profile projects often fail at API security best practices.

The Financial and AI Risk

The risk profile for exposed keys has shifted dramatically with the rise of LLMs. Previously, an exposed Google Maps key might just result in a slightly higher bill. Today, keys once considered relatively harmless in client-side code can now authenticate to AI services like Gemini, allowing attackers to use your quota for their own malicious AI agents or rack up massive charges.

In SimplyScan's corpus, security issues (high) appeared in 10% of scanned apps. For an AI-built startup, a single leaked OpenAI or AWS key can lead to immediate exploitation. Attackers often use leaked cloud credentials to spin up expensive GPU instances for crypto mining, which can result in significant financial liability before the owner even notices the breach.

Which API Keys Are Safe to Put in the Frontend?

Not every string labeled "API Key" is a secret. Developers must distinguish between "Publishable" identifiers and "Secret" credentials.

Publishable Keys (Safe for Frontend)

These keys are designed to be public. They usually have built-in protections like domain whitelisting.

  • Stripe Publishable Key: Starts with pk_. It only allows the frontend to tokenize credit card info; it cannot move money.
  • Firebase Config: The apiKey in a Firebase config object is an identifier, not a secret. Security is handled via Firebase security rules.
  • Google Maps API Key: Safe ONLY if you have configured "HTTP Referrer" restrictions in the Google Cloud Console.
  • Posthog/Segment/Mixpanel Tokens: These are write-only tokens used to send telemetry.

Secret Keys (Never Put in Frontend)

These keys grant administrative or data-access privileges.

  • Stripe Secret Key: Starts with sk_. Can issue refunds and view customer data.
  • OpenAI/Anthropic Keys: Grant full access to your AI credits and fine-tuned models.
  • Database URLs: Any string containing postgres:// or mongodb+srv:// exposes your entire database to code injection and data theft.
  • AWS Secret Access Keys: Allows attackers to control your cloud infrastructure.

How Do You Check Your Code for Exposed Keys?

1. Automated Scanning

The most efficient way to find leaks is to use a dedicated scanner. SimplyScan's secret scanner detects AWS, Stripe, OpenAI, and GitHub key formats in seconds. Because AI-built apps often have complex dependency trees, manual searching is rarely enough.

2. Manual Grep Search

Search your local codebase for common patterns before you commit:

3. Inspecting the Build Bundle

Build tools like Vite or Webpack often "inline" environment variables. Even if your source code looks clean, your dist/ folder might contain the secret.

  • Run npm run build.
  • Open the resulting .js files in your dist or build folder.
  • Search for your secret key string. If it's there, your configuration is leaking.

4. Checking Git History

A key is compromised the moment it is pushed to a remote repository, even if you delete it in the next commit. If you accidentally committed a key, you must rotate it and remove secrets from git history.

How Do You Fix an Exposed API Key?

If you find an exposed key, follow these steps in order. Do not just delete the code; the key is already "burned."

Step 1: Rotate the Key

Go to the provider's dashboard (e.g., OpenAI, Stripe, AWS). Generate a new key and immediately revoke/delete the old one. This is the only way to stop active exploitation.

Step 2: Implement a Backend Proxy

Instead of calling the third-party API from the browser, call your own server. Your server then makes the request using the secret key stored safely in its environment variables.

Wrong (Frontend):

Right (Frontend):

Right (Backend/Edge Function):

Step 3: Add Rate Limiting and Auth

Once you move the key to the server, your proxy endpoint becomes a target. If it's unprotected, an attacker can still "drain" your API credits by spamming your proxy. Ensure your proxy requires user authentication and has strict rate limits.

How Different Frameworks Handle Environment Variables

Modern frameworks try to prevent accidental leaks by using prefixes. If you don't use the prefix, the variable isn't sent to the browser.

  • Vite: Only variables starting with VITE_ are exposed. If you store your key in VITE_OPENAI_KEY, it will be leaked. Use OPENAI_KEY (no prefix) and access it only in server-side code.
  • Next.js: Only variables starting with NEXT_PUBLIC_ are exposed. Use Next.js security best practices to keep secrets in API routes or Server Components.
  • Create React App: Only variables starting with REACT_APP_ are bundled.
  • Nuxt: Uses a runtimeConfig object. Variables in public are exposed; variables in the root runtimeConfig are server-only.

Prevention and Best Practices for Vibe-Coded Apps

When building with AI tools like Bolt or Lovable, the speed of development often outpaces security checks. In SimplyScan's data, architecture issues (medium) appeared in 48% of apps, often because the AI suggested a client-side-only architecture for features that require a backend.

  • Use a .gitignore: Ensure .env and .env.local are always ignored. Use our gitignore generator to get a safe baseline.
  • Pre-commit Hooks: Use tools like husky and secret-lint to block commits that contain high-entropy strings or known key formats.
  • Least Privilege: If an API provider allows it, create "restricted" keys. For example, an AWS key that can only upload to one specific S3 bucket is much safer than an admin key.
  • Continuous Monitoring: Use uptime monitoring and scheduled security scans to detect regressions. A feature update might accidentally introduce a leak that wasn't there at launch.

The Bottom Line

Exposed API keys are the "low hanging fruit" for hackers. Whether you are building a simple wrapper or a complex SaaS, the rule is absolute: Secrets stay on the server.

If you are unsure if your site is currently leaking credentials, run a free security scan. It takes ~30 seconds to check for exposed API keys, missing security headers, and common code injection vulnerabilities.

Related Free Tools

FAQ

Is the Firebase API key safe to expose in frontend code?

Yes, the Firebase apiKey found in the web configuration object is generally safe to include in your frontend code. Unlike a secret key, it is used to identify your project to Google's servers. However, this safety relies entirely on you configuring Firebase Security Rules for Firestore and Storage. Without those rules, the API key allows anyone to read or delete your entire database.

Are VITE_ or NEXT_PUBLIC_ environment variables actually secret?

No. Any environment variable prefixed with VITE_ (Vite) or NEXT_PUBLIC_ (Next.js) is explicitly designed to be bundled into the JavaScript sent to the user's browser. They are "public" by definition. You should only use these for non-sensitive values like an API base URL or a public tracking ID. Never put secret keys or database passwords in these variables.

What should I do first if my API key was leaked?

The very first step is to rotate the key: generate a new one and revoke the old one in the provider's dashboard. Deleting the code is not enough because the key is already in the hands of bots. After rotating, move the new key to a server-side environment and update your application to use a proxy. Finally, check your Git history to ensure the secret isn't still visible in past commits.

Can attackers find keys in my git history even after I deleted them?

Yes. Git is a version control system that records every change. If you commit a secret key and then delete it in a later commit, the key still exists in the repository's history. Anyone who clones the repo or views it on GitHub can browse previous commits to find it. You must use a tool like BFG Repo Cleaner or git filter-repo to scrub the history.

How quickly are exposed API keys exploited?

Exploitation often happens within seconds or minutes. Large-scale attackers monitor the GitHub "Public Timeline" API and crawl new websites as soon as they are indexed. For high-value targets like AWS or OpenAI, automated scripts will attempt to use the key for crypto mining or model-theft immediately upon discovery. Speed is critical when responding to a leak.

Why do AI code generators expose API keys so often?

AI tools like ChatGPT, Claude, or Bolt often prioritize creating a "ready-to-run" demo. The simplest way to make an API call work in a single-file React demo is to hardcode the key. AI models don't always "know" your specific deployment environment, so they default to the most direct (and least secure) path. Always audit AI-generated code for hardcoded strings before deploying.

Frequently asked questions

Is the Firebase API key safe to expose in frontend code?

Yes, the Firebase apiKey found in the web configuration object is generally safe to include in your frontend code. Unlike a secret key, it is used to identify your project to Google's servers. However, this safety relies entirely on you configuring Firebase Security Rules for Firestore and Storage. Without those rules, the API key allows anyone to read or delete your entire database.

Are VITE_ or NEXT_PUBLIC_ environment variables actually secret?

No. Any environment variable prefixed with VITE_ (Vite) or NEXT_PUBLIC_ (Next.js) is explicitly designed to be bundled into the JavaScript sent to the user's browser. They are "public" by definition. You should only use these for non-sensitive values like an API base URL or a public tracking ID. Never put secret keys or database passwords in these variables.

What should I do first if my API key was leaked?

The very first step is to rotate the key: generate a new one and revoke the old one in the provider's dashboard. Deleting the code is not enough because the key is already in the hands of bots. After rotating, move the new key to a server-side environment and update your application to use a proxy. Finally, check your Git history to ensure the secret isn't still visible in past commits.

Can attackers find keys in my git history even after I deleted them?

Yes. Git is a version control system that records every change. If you commit a secret key and then delete it in a later commit, the key still exists in the repository's history. Anyone who clones the repo or views it on GitHub can browse previous commits to find it. You must use a tool like BFG Repo Cleaner or git filter-repo to scrub the history.

How quickly are exposed API keys exploited?

Exploitation often happens within seconds or minutes. Large-scale attackers monitor the GitHub "Public Timeline" API and crawl new websites as soon as they are indexed. For high-value targets like AWS or OpenAI, automated scripts will attempt to use the key for crypto mining or model-theft immediately upon discovery. Speed is critical when responding to a leak.

Why do AI code generators expose API keys so often?

AI tools like ChatGPT, Claude, or Bolt often prioritize creating a "ready-to-run" demo. The simplest way to make an API call work in a single-file React demo is to hardcode the key. AI models don't always "know" your specific deployment environment, so they default to the most direct (and least secure) path. Always audit AI-generated code for hardcoded strings before deploying.

Related guides

  • How to Find Exposed API Keys in a Lovable App · To find exposed API keys in a Lovable app, inspect the browser's Network and Sources tabs for hardcoded strings like "sk-" or "AIza". AI-generated apps often leak secrets by making direct frontend calls to services like OpenAI or Stripe. Use SimplyScan to automatically detect these leaks and rotate compromised keys immediately.
  • How to Fix Exposed API Keys in 5 Minutes · Revoke the exposed key at the provider dashboard immediately to stop exploitation. Then, audit usage logs for abuse, move the API call to a server-side proxy (like an Edge Function), and store the new key as a secure environment variable without public prefixes. Act fast to prevent financial loss.
  • AI API Security · Protecting LLM-Powered Apps, Keys, and Endpoints · AI API security involves protecting LLM keys (OpenAI, Anthropic) and hardening the endpoints you build. To secure your app, keep keys server-side in a proxy, implement per-user rate limits to prevent "denial of wallet" attacks, and sanitize all model outputs to block XSS and prompt injection.
  • How to Find Exposed Secrets in Your Code Before They Ship · Exposed secrets hide in three predictable places: frontend bundles, git history, and misprefixed .env files. Grep your code and built output for known prefixes like sk_live_, AKIA, and ghp_, then use an automated secret scanner to catch high-entropy leaks. If you find one, rotate the key immediately to end the exposure.

All security guides · Free security tools · Platform scanners · Security checklist