Beamfar

Leaked API keys in frontend JavaScript: how secrets reach production and how to rotate them

A leaked API key in frontend JavaScript is one of the fastest ways a healthy web application turns into an expensive billing incident or a data breach. Automated crawlers continuously fetch newly deployed HTML pages, bundled scripts, and source maps looking for high-value key prefixes. When a secret appears in public output, automated abuse can begin within minutes.

How secrets slip into public web pages

Most credential leaks are unintentional. They happen because modern full-stack frameworks blur the visual line between server code and browser code inside the same repository.

1. Client-exposed environment prefixes

Build tools such as Next.js, Vite, Nuxt, and Astro intentionally inline environment variables that match a public prefix (NEXT_PUBLIC_, VITE_, NUXT_PUBLIC_, PUBLIC_) directly into the compiled JavaScript sent to every visitor. When a developer or AI coding tool renames a variable to silence a client-side undefined error, the secret gets baked verbatim into static bundle files on your CDN.

2. Server props serialized into HTML

Server-rendered frameworks pass initial data from server loaders into client hydration scripts such as <script id="__NEXT_DATA__"> or __NUXT__. Passing an entire configuration object, user record, or database query result into page props can silently write internal tokens, webhook secrets, or signed URLs straight into the HTML document source.

3. Direct browser calls to paid AI or email APIs

During early prototyping, it is tempting to call OpenAI, Anthropic, Resend, or SendGrid straight from a React component with fetch(). Shipping that prototype without moving the request to a backend API route hands every visitor full access to your API quota and account permissions.

4. Exposed .env files and production source maps

Static hosting misconfigurations or copied server directories sometimes leave /.env, /.env.production, or .js.map files readable over HTTP. Even when a bundle was minified, a public source map restores original filenames, comments, and environment references.

Check it now. The frontend secret leak checker scans public HTML, __NEXT_DATA__ and up to four first-party JavaScript bundles across 12 live credential families without storing any secret; the security headers checker reads a page’s HSTS, CSP, X-Content-Type-Options, frame protection, Referrer-Policy and Permissions-Policy. No account, and the address is not stored.

Public keys vs secret keys: what belongs in the browser

Not every token visible in browser network traffic is a vulnerability. Separating publishable identifiers from privileged secrets prevents wasted triage and missed emergencies.

  • Stripe: publishable keys (pk_live_, pk_test_) are designed for browser checkout elements, as documented in Stripe’s API keys guide. Secret keys (sk_live_) and restricted live keys (rk_live_) belong strictly on the server.
  • Supabase: the anon JWT is intended for browser clients when Row Level Security (RLS) policies enforce access rules on every table. The service_role JWT bypasses RLS completely and must never reach the browser.
  • AWS: temporary scoped credentials or signed upload URLs with short expiries may be issued per request, while long-lived IAM access keys (AKIA...) must stay server-side, per AWS IAM best practices.
  • AI providers, mailers and databases: OpenAI (sk-proj-...), Anthropic (sk-ant-...), GitHub (ghp_, github_pat_), GitLab (glpat-), SendGrid (SG.), Resend (re_), Slack incoming webhooks, PEM private keys, and PostgreSQL or MongoDB connection URLs containing passwords should never appear in HTML, client JS, or public config files.

Step-by-step response when a live key leaks

If a scan, teammate, or provider notice alerts you that a production credential appeared on a live site, follow this order so you stop exposure without causing avoidable downtime.

Step 1: Rotate or revoke first, clean up code second

Deleting the key from your Git repository or pushing a new frontend build does not invalidate a credential that crawlers or browser caches already copied. Follow the OWASP Secrets Management Cheat Sheet rule: assume any publicly rendered secret was captured.

  1. Generate a replacement key in the provider dashboard with the narrowest permissions required.
  2. Update your server-side environment store (Vercel, Cloudflare Workers, Hetzner systemd env, Docker secrets, or cloud secret manager) and redeploy the backend.
  3. Revoke the leaked key immediately once the replacement serves traffic. If the leaked key is already being abused, revoke it before waiting for a graceful rollout.

Step 2: Move the integration behind a server boundary

Create a server route or edge function that validates the caller’s session, applies rate limits, and invokes the upstream provider using a non-public environment variable. Return only the minimal fields the UI needs.

Step 3: Check provider logs and billing usage

Inspect API request logs, IAM CloudTrail events, database audit logs, and usage dashboards covering the full window from the deploy that introduced the key until revocation. Look for unfamiliar IP ranges, newly created tokens, unauthorized data exports, or unexpected model calls.

Step 4: Purge CDN caches and verify the live page

After deploying the cleaned frontend build, purge stale HTML and static asset caches at your CDN so edge nodes stop serving older bundles. Fetch the live page and verify that neither the HTML nor hydrated state contains the credential pattern.

Prevent regressions after every deploy

One manual grep before launch rarely holds up across dozens of weekly releases. Combine three lightweight safeguards:

  1. Pre-commit and CI checks that refuse commits containing high-entropy vendor secret patterns before code merges.
  2. Strict environment naming where CI fails if a known secret variable name is ever referenced inside client bundle files.
  3. Continuous outside inspection on the live deployed URL, because misconfigured hosting, reverse proxies, and CDN overrides only show up in production responses.

On paid plans (Solo, Team, Agency, and Agency Plus), Beamfar inspects live HTML pages, inline scripts, and hydrated page state passively for leaked production credentials—recording only the provider, a non-secret masked prefix, and coarse location without ever storing the secret value itself—and pairs that with verified exposure probes (/.env, /.git/HEAD, .js.map) once domain ownership is proved. Check what your site currently shows from outside with a free site check, or compare monitoring tiers on pricing.

Sources

Read on . Standards and vendor pages change; confirm the current text before you rely on it.

Terms used in this guide

  • HSTSHSTS is a response header telling browsers to use only HTTPS for a site. What max-age and includeSubDomains do, and why an expired certificate then hurts.
  • TLS certificateA TLS certificate proves a website holds the name in the address bar and enables HTTPS. What it contains, how long it lasts, what expiry breaks.
  • IncidentAn incident is a period in which a monitored site is confirmed to be failing, from first confirmation to recovery. What an incident record should hold.

Try it on your own sites.

Add your sites: checking starts as soon as you do.

No card for the Free plan.