Why Exposed API Keys in Frontend Code Are Dangerous

Quick answer: Secret API keys embedded in frontend JavaScript are readable by anyone who receives the bundle. Exposure can enable misuse within the credential’s permissions. Revoke or rotate exposed secrets, remove public copies, and protect server-side API calls with authorization and usage limits.

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. An exposed credential can enable unauthorized requests within its permissions and contribute to data loss or unexpected usage charges.

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 receives the resources needed to render and run that page, including its JavaScript. 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. Review generated code and deployment configuration independently of whether the visible features work.

These live figures describe all scanned sites. They do not establish prevalence for an AI-built subgroup, compare development methods, or attribute findings to AI generation.

30% of the 119 live sites SimplyScan has scanned (36 sites) have at least one high or critical security issue.

How Attackers Find Your Keys

Use browser DevTools to inspect downloaded scripts and network responses. Search for indicators such as sk_, api_key, or bearer, then verify whether a match is a live secret, public identifier, or harmless example.

Pattern checks can flag credential-like strings, including:

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

A report on exposed Algolia credentials describes 39 Algolia Admin API keys embedded in frontend JavaScript on open-source documentation sites. The example concerns administrative credentials, not public search-only identifiers. Review API security best practices for credential handling.

The Financial and AI Risk

Review each key’s allowed APIs and restrictions. A publicly exposed Google API key that permits access to Gemini can expose billable usage; a browser key restricted to its intended API has a different scope. Keep credentials for server-side AI requests out of browser code.

13% of the 119 live sites SimplyScan has scanned (15 sites) have at least one high-severity web-security issue, such as a missing Content-Security-Policy or HSTS header.

The web-security category above does not measure exposed-key prevalence. Assess any exposed credential’s permissions, review its usage logs, and revoke or rotate it promptly.

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)

Follow each provider’s intended client-side use and apply the relevant API and application restrictions. A public identifier does not replace authorization.

  • Stripe Publishable Key: Starts with pk_ and is intended for client-side Stripe integrations. Keep secret API credentials on the server.
  • 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: For browser integrations, configure website restrictions and restrict the key to the required Maps APIs.
  • Analytics Project Tokens: Distinguish public ingestion identifiers from personal or administrative credentials using the provider’s documentation.

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: Authorize requests within their assigned project and permission scope; keep them server-side.
  • Database URLs: Keep connection strings containing secret credentials server-side, including credential-bearing postgres:// and mongodb+srv:// URLs; access depends on the credential’s permissions and network reachability.
  • AWS Secret Access Keys: Together with the associated access key ID and any required session token, authorize requests subject to IAM permissions.

How Do You Check Your Code for Exposed Keys?

1. Automated Scanning

SimplyScan’s secret scanner has pattern checks for AWS, Stripe, OpenAI, and GitHub credentials. Use its URL or repository checks alongside manual inspection, and review coverage limitations and ambiguous matches.

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

Treat a secret committed to a shared repository as exposed to anyone with access, even if a later commit deletes it. 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. Verify that the exposed credential is disabled, review related activity, and address any additional access the incident created.

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

Framework prefixes identify values intended for client use, but removing a prefix is not proof of secrecy. Code, build configuration, or server responses can still expose a value. Inspect the deployed output.

  • Vite: The default client environment prefix is VITE_. A secret supplied as VITE_OPENAI_KEY can enter the browser bundle. Keep OPENAI_KEY in server-side code and inspect custom build settings too.
  • Next.js: NEXT_PUBLIC_ values referenced by client code are inlined at build time. Keep secrets in server-only code and avoid returning them in rendered output or API responses; see Next.js security best practices.
  • Create React App: Custom variables exposed through REACT_APP_ must contain only public values; inspect build configuration and output too.
  • 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

Review secrets, permissions, and build configuration directly. The architecture statistic below is an aggregate category; it does not identify exposed keys or their cause.

11% of the 119 live sites SimplyScan has scanned (13 sites) have at least one medium-severity architecture issue, such as a library with a known vulnerability or no rate limiting.

Use a .gitignore

Ensure .env and .env.local are always ignored. Use our gitignore generator to get a safe baseline.

Pre-commit Hooks

Configure a pre-commit hook to run a supported secret-pattern check. A hook manager such as husky can invoke the chosen check; a task named secret-lint has no defined protection unless you configure its implementation. Verify that the hook runs in your workflow and review what it covers.

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 for availability and scheduled security scans for supported security signals. 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

  • Secret Scanner · Checks supported URL and repository sources for credential patterns.
  • Env File Linter · Checks your .env files for formatting and security errors.
  • Exposed Files Scanner · Probes supported sensitive paths, including .git metadata and .env files, and distinguishes confirmed exposure from inconclusive responses.
  • Inspect the deployed security headers and test their intended browser protections. Header checks do not establish that all injection or data-leak risks are covered. See Security Headers Check.

FAQ

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

The Firebase apiKey identifies the project and is intended for client use when restricted to the relevant Firebase APIs. Protect Firestore and Storage data with Firebase Security Rules and the intended authentication checks; use App Check where supported. Test permitted and denied reads and writes with private test data. Do not use a public Firebase key to authorize unrelated billable APIs.

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?

Revoke or rotate the exposed key promptly and verify that it no longer works. Remove exposed copies, deploy the replacement only in server-side configuration, and review usage logs for misuse. Protect any proxy with authorization and usage limits; inspect repository history and deployed bundles for remaining copies.

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?

The timing cannot be inferred from an exposed key alone. Do not wait for evidence of misuse: revoke or rotate it, inspect provider logs and billing, and remove exposed copies. The impact depends on the credential’s permissions and whether it was used.

How should I check AI-generated code for exposed keys?

Inspect generated code for hardcoded secrets and review what the build exposes. This article’s scan statistics do not establish how often particular AI tools expose credentials or why a model produced a specific implementation.

Frequently asked questions

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

The Firebase apiKey identifies the project and is intended for client use when restricted to the relevant Firebase APIs. Protect Firestore and Storage data with Firebase Security Rules and the intended authentication checks; use App Check where supported. Test permitted and denied reads and writes with private test data. Do not use a public Firebase key to authorize unrelated billable APIs.

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?

Revoke or rotate the exposed key promptly and verify that it no longer works. Remove exposed copies, deploy the replacement only in server-side configuration, and review usage logs for misuse. Protect any proxy with authorization and usage limits; inspect repository history and deployed bundles for remaining copies.

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?

The timing cannot be inferred from an exposed key alone. Do not wait for evidence of misuse: revoke or rotate it, inspect provider logs and billing, and remove exposed copies. The impact depends on the credential’s permissions and whether it was used.

How should I check AI-generated code for exposed keys?

Inspect generated code for hardcoded secrets and review what the build exposes. This article’s scan statistics do not establish how often particular AI tools expose credentials or why a model produced a specific implementation.

Related guides

  • How to Secure Your Google API Key: Preventing Leaks in AI-Generated Frontend Code · Identify which Google service and credential type your app uses before deciding what must remain secret. Keep Gemini credentials server-side, restrict intended browser keys appropriately, and test backend permissions and usage controls. Review source, build output, and provider settings; a scanner cannot establish every key’s effective restrictions.
  • How to Find Exposed API Keys in a Lovable App · Inspect a Lovable app’s browser-visible bundles and requests for secret credentials. Prefix matches are clues, not proof that a value is a valid secret. Keep privileged credentials on a protected backend, review repository history, and revoke any secrets that were exposed.
  • How to Fix Exposed API Keys · If a secret API key leaks, revoke it through the provider, investigate its use, and repair the exposure path. Store replacements server-side and test authorized integrations. Deleting a file does not invalidate copied credentials or undo prior access.
  • How to Secure Groq and Gemini API Keys: Preventing Frontend Leaks in AI Apps · Keep standard Groq and Gemini API keys on the server and protect the endpoint that uses them. Public build-variable prefixes can expose secrets in browser bundles. Review authentication, authorization, validation and usage limits, and use provider-supported temporary credentials only where explicitly intended.

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