Skip to content
FunnelGuard

Fix guide by FunnelsGuard

API keys leaked in frontend JavaScript: how to find and fix it

OPS-182High impactDetectedBy FunnelGuardPublished Updated
On this page

What this issue is

Frontend JavaScript is the code your site sends to every visitor's browser. Anyone can read it with View Source or the browser's DevTools. If a developer, plugin or theme puts a secret key in that code, the key is no longer secret.

Not every key is equally dangerous. Some keys are designed to be public. Others give full control of an account.

Which keys are safe in the browser
KeyLooks likeSafe in frontend?
Stripe publishable keypk_live_...Yes, by design
Stripe secret keysk_live_...Never
Stripe restricted keyrk_live_...No, keep it server-side
Mailchimp API key32 characters, then -us21 (or another data centre)Never
Google Maps JavaScript keyAIza...Yes, only if restricted by HTTP referrer and API
Google key for paid or server APIsAIza...Not unless tightly restricted

Why it costs you leads or sales

Bots scan public websites and code repositories for key patterns. A leaked key can be used within hours, so treat any exposure as a live incident.

- Stripe secret key: an attacker can read customer data, create charges or refunds, and change account settings. - Mailchimp key: an attacker can export your subscriber list, send campaigns in your name, or delete the audience. That harms your list and your sender reputation. - Google key: others can run up usage on your billing account, or your quota runs out and your maps, address autocomplete or reCAPTCHA-style features stop working for real visitors.

How a leaked key becomes a business problem
  1. Key added to JSSecret placed in a script or inline config
  2. Page servedEvery visitor downloads the key
  3. Key scrapedA bot or person copies it
  4. Account misusedCharges, list export, quota abuse

The break is the moment the secret is placed in browser code.

How to check if your site has it

Look for exposed keys yourself
  1. Search the page source

    Open your key pages (checkout, forms, landing pages), press Ctrl+U (Cmd+Option+U on Mac) and search for sk_live, sk_test, rk_live, AIza, and -us followed by digits.

  2. Search the loaded scripts

    In DevTools open Sources (Chrome) or Debugger (Firefox). Use the global search (Ctrl+Shift+F) across all loaded files for the same patterns plus the words apiKey, api_key, secret and token.

  3. Check the Network tab

    Reload with the Network tab open. Look at request URLs and headers for keys in query strings or Authorization headers sent directly from the browser to Stripe, Mailchimp or other APIs.

  4. Check source maps

    If a file ends with //# sourceMappingURL, the map may reveal original code including environment variables baked in at build time.

  5. Scan your code repository

    Search your repo and its history for the same patterns. GitHub secret scanning and open-source tools such as gitleaks or trufflehog can do this automatically.

Quick scan of a page and its scripts for key patternsbash
curl -s https://example.com/ | grep -Eo 'sk_live_[0-9A-Za-z]+|rk_live_[0-9A-Za-z]+|AIza[0-9A-Za-z_-]{35}|[0-9a-f]{32}-us[0-9]+'
# repeat for each script URL found in the page

How to fix it

Fix a leaked key in order
  1. Rotate the key immediately

    Stripe: Developers > API keys, roll the secret key (you can set an expiry for the old one). Mailchimp: Account > Extras > API keys, create a new key and disable the old one. Google: Google Cloud Console > APIs & Services > Credentials, create a new key and delete the old one.

  2. Review account activity

    Check Stripe logs and payments, Mailchimp audience exports and campaigns, and Google Cloud billing and API usage for activity you do not recognise.

  3. Move the call to the server

    The browser should call your own endpoint, and your server should call Stripe or Mailchimp with the secret stored in an environment variable or the platform's secrets store.

  4. Restrict keys that must stay public

    In Google Cloud Console open the key, set Application restrictions to HTTP referrers (your domains) and API restrictions to only the APIs you use. Set a budget alert.

  5. Remove the key from code and history

    Delete it from the files, disable source maps in production if they expose it, and purge it from git history if the repo is shared. Rotation matters more than purging.

Where the secret usually hides, by platform
  1. Check plugin and theme settings

    Search theme files and Custom HTML or header/footer script boxes for key patterns. Some plugins print keys into page source through wp_localize_script.

  2. Use the server for secrets

    Store secrets as constants in wp-config.php (define('MAILCHIMP_KEY', '...');) and call the API from PHP, not from enqueued JavaScript.

Before and after: subscribe a visitor without exposing the Mailchimp key (Node.js, Express)javascript
// BAD: runs in the browser, key is public
// fetch('https://us21.api.mailchimp.com/3.0/lists/LIST_ID/members', {
//   headers: { Authorization: 'Bearer ' + 'YOUR_SECRET_KEY' }
// });

// GOOD: browser calls your server
// Browser:
fetch('/api/subscribe', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ email })
});

// Server (secret read from environment):
app.post('/api/subscribe', async (req, res) => {
  const r = await fetch('https://us21.api.mailchimp.com/3.0/lists/' + process.env.MC_LIST_ID + '/members', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: 'Bearer ' + process.env.MC_API_KEY
    },
    body: JSON.stringify({ email_address: req.body.email, status: 'subscribed' })
  });
  res.status(r.ok ? 200 : 502).end();
});
Key handling

Leaked

  • Secret key sits in a script the browser downloads
  • Anyone can copy it from View Source
  • Old key never rotated

Fixed

  • Secret stored as a server environment variable
  • Browser calls your own endpoint only
  • Old key disabled, public keys restricted

How to confirm it's fixed

Fix verification
  • The old key is disabled or deleted in the provider dashboard
  • Searching page source and all loaded scripts finds no sk_live, rk_live or Mailchimp key patterns
  • Remaining Google keys show referrer and API restrictions in Cloud Console
  • Checkout, signup and map features still work with the new setup
  • Provider logs show no unknown activity after rotation
  • Source maps in production do not reveal secrets

How to prevent it happening again

Prevention habits
  • Keep secrets only in server environment variables or a secrets manager
  • Never use public-prefixed env variables (NEXT_PUBLIC_, VITE_) for secrets
  • Turn on GitHub secret scanning or run gitleaks in CI
  • Use restricted keys with the fewest permissions the job needs
  • Set budget and quota alerts on Google Cloud
  • Review third-party scripts and plugin updates before installing them
  • Rotate keys when a developer or agency leaves

How FunnelGuard handles this

FunnelGuard does not check for exposed API keys in frontend JavaScript today. It is a possible future check, not a current feature.

What FunnelGuard does do is run your real customer journeys (lead forms, checkouts, booking and chat buttons) on a schedule, check each step and the tracking hits sent to ad and analytics platforms, and confirm test leads reach your inbox and CRM. That helps you notice if a key rotation breaks a form, checkout or signup step, but it does not tell you a secret is exposed.

Time matters after a leakExample numbers
Time matters after a leak (example)Key published: 0 hours; Bot scrapes key: 2 hours; First misuse: 6 hours; You notice (no alerts): 72 hours0285502672Key publishedBot scrapes keyFirst misuseYou notice (no alerts)hours

Example: illustrative hours between exposure and first misuse, showing why you rotate before cleaning up.

Questions people ask

Is it safe to put a Stripe key in JavaScript?

Only the publishable key (starts with pk_) is safe in the browser. The secret key (sk_live_) and restricted keys (rk_live_) must stay on your server. If a secret key was ever in frontend code, roll it in the Stripe Dashboard under Developers > API keys.

How do I find API keys exposed on my website?

Open the page source and DevTools Sources, then search for patterns such as sk_live, AIza and a 32-character key ending in -us plus digits. You can also scan your code repository with gitleaks or trufflehog, and check the Network tab for keys sent from the browser.

Is a Google Maps API key in my page source a problem?

Not by itself. Google Maps JavaScript keys are meant to be visible, but you must restrict them to your domains with HTTP referrers and to only the APIs you use. An unrestricted key can be copied and used on your billing.

What should I do if my Mailchimp API key was exposed?

Create a new key under Account > Extras > API keys and disable the old one straight away. Then check your audience for exports or unexpected campaigns, and move subscribe calls to server-side code.

Is deleting the key from my code enough?

No. The key may already have been copied, and it can remain in git history, caches and source maps. Rotate it so the old value stops working, then remove it from code.

Why is my frontend JavaScript showing environment variables?

Build tools inline some variables into the browser bundle, such as those prefixed NEXT_PUBLIC_ or VITE_. Anything with those prefixes is public. Keep secrets in variables without the prefix and read them only in server code.

Does FunnelGuard detect leaked API keys?

No. FunnelGuard does not check for this yet, and it is a possible future check. It does monitor your forms, checkouts and tracking, which can show if a key rotation broke a journey.

Does FunnelGuard catch this?

Detected

FunnelGuard checks for this today.

How: site safety (Stage 26, daily): Stripe secret, AWS, private keys, Slack, Mailchimp, SendGrid in the page and its own scripts.

Stop finding out from your customers

FunnelGuard runs your real forms and checkouts on a schedule, checks the tracking and the leads behind them, and alerts you once, with a screenshot. Try any paid plan free for 3 days.