← All articles

The Free Way to Scan Your JavaScript Bundles for Leaked API Keys

Every JavaScript file your app sends to the browser is public. Anyone can open DevTools, pull your bundles, and search them for strings that look like credentials, and plenty of people do this as a matter of routine. In pentests and bug bounty work, a secret key sitting in a minified main.js is one of the most common high-impact findings, and one of the easiest to prevent. This guide covers how secrets get into frontend bundles, which keys are actually safe to ship, how to check your own builds by hand, and what to do when you find one. If you want the quick version, point our JS Secrets Scanner at a domain you've verified and it will crawl and analyze the JavaScript your site actually serves.

Why secrets end up in frontend bundles

Bundlers aren't leaking anything by mistake. They do exactly what they're configured to do. The problem is that the configuration rules are easy to misread.

Public env prefixes are a build-time copy-paste

Modern frameworks decide which environment variables go into the browser based on a name prefix:

The usual failure: a client-side call returns undefined, so someone renames OPENAI_API_KEY to NEXT_PUBLIC_OPENAI_API_KEY. It works, the PR merges, and the key now ships to every visitor. Prefixes tell the bundler to publish the value. They don't make it safe to publish.

Hard-coded fallbacks and copied config

Other common sources:

  • Defaults like const key = process.env.API_KEY || "sk_live_..." left over from local testing.
  • Server-only config files (config.ts, constants.js) imported by a client component. The bundler follows the import and pulls the whole module in.
  • Third-party SDK init snippets pasted with an admin or secret token instead of the public or browser token.

Source maps expose what minification hid

Production source maps make the leak bigger. A .map file usually includes the original, unminified source, so comments, internal endpoints, and any secrets that tree-shaking removed from the final bundle can still be read in the map. Both major frameworks turn production browser source maps off by default. Next.js only emits them if you set productionBrowserSourceMaps: true, and Vite's build.sourcemap defaults to false. Teams often switch them on to get readable stack traces in an error tracker and then forget the files are publicly served. If you need maps for an error-reporting tool, Vite's 'hidden' option produces them without the sourceMappingURL comment. You still have to keep the .map files off your public origin or block them there.

Which keys are safe to expose (and which are not)

Not every key in a bundle is a vulnerability. Some are designed to be public. The question is whether the key grants access by itself or only identifies your project while server-side rules enforce access.

KeySafe in frontend?Why
Stripe publishable key (pk_live_, pk_test_)YesStripe says it's safe to embed in client-side code
Stripe secret key (sk_live_) or restricted key (rk_live_)NoStripe calls server-side keys sensitive; they can create charges, refunds, and read customer data
Firebase web config apiKeyUsually, with caveatsFirebase API keys aren't used to control access to backend resources; Security Rules and App Check do that
Firebase / GCP service account JSONNoFull server credentials that bypass Security Rules
Google Maps browser keyYes, if restrictedNeeds application and API restrictions
AWS access key (AKIA...) + secretNoDirect IAM credentials
OpenAI, Anthropic, or other LLM API keysNoBillable and often tied to stored data
Supabase publishable key (sb_publishable_, legacy anon)Yes, if RLS is onSupabase says it only reaches what Row Level Security allows
Supabase secret key (sb_secret_, legacy service_role)NoBypasses Row Level Security

The Google API key caveat

Google API keys deserve a closer look. Firebase's documentation now warns that a key in your web config should only allow Firebase-related APIs, and that the Generative Language API should not be in its allowlist. The reason: Truffle Security showed that if the Gemini API is enabled on a Google Cloud project, existing unrestricted keys in that project, including keys sitting in public JavaScript, could call Gemini endpoints. Google has since moved Gemini to service-account-backed "auth keys". The lesson still holds. A "public" key is only safe while its restrictions are tight, so check the API and referrer restrictions on every Google key you ship.

Manual checks: scan your own built assets

You can do all of this with free tools. Start with the build output, because that's the closest thing to what users download.

1. Find which env vars are marked public

grep -rnE '^(NEXT_PUBLIC_|VITE_|REACT_APP_)' .env* 2>/dev/null

Read every match and ask whether the value would be fine on a billboard. Words like SECRET, PRIVATE, ADMIN, SERVICE_ROLE, or TOKEN in a public variable name are an immediate red flag.

2. Build and grep the output

Build the production bundle, then search it. Next.js writes client assets to .next/static, and Vite writes to dist/.

npm run build
grep -rEoh 'sk_live_[0-9a-zA-Z]{10,}|rk_live_[0-9a-zA-Z]{10,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{35}|ghp_[0-9A-Za-z]{36}|xox[baprs]-[0-9A-Za-z-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----' dist/ .next/static/ 2>/dev/null | sort -u

These patterns cover Stripe live secret and restricted keys, AWS access key IDs, Google API keys, GitHub classic tokens, Slack tokens, and PEM private keys. Regex alone won't catch generic high-entropy strings, which is why the dedicated scanners below are worth running too.

3. Check for shipped source maps

# Are maps generated?
find dist .next/static -name '*.map' 2>/dev/null | head

# Do bundles reference them?
grep -rl 'sourceMappingURL' dist .next/static 2>/dev/null | head

# Are they served in production? (replace with a real bundle path)
curl -s -o /dev/null -w '%{http_code}\n' https://app.example.com/assets/index-abc123.js.map

A 200 on the last command means anyone can download your original source. Grep the map files with the same patterns as above, because they can contain strings that never made it into the minified output.

4. Run gitleaks and trufflehog against the build directory

Gitleaks has a dir command for scanning plain files instead of git history:

brew install gitleaks
gitleaks dir -v dist/

TruffleHog scans directories with filesystem and can filter by verification status:

brew install trufflehog
trufflehog filesystem dist/ --results=verified,unknown

TruffleHog's verification checks whether a detected credential is live by calling the provider's API with it. That's useful for triage, but it means the tool makes outbound requests using the key it found. Use --no-verification if that's a problem in your environment.

Run both against git history as well (gitleaks git, trufflehog git file://.). A key removed from the current bundle but still present in an old commit has still leaked.

5. Check what production actually serves

Production can differ from local builds (CI env vars, CDN-injected scripts, stale deploys). Compare against the live page's script tags:

curl -s https://app.example.com/ | grep -oE 'src="[^"]+\.js"'

Lazy-loaded chunks don't show up in the initial HTML, so this only gives you a partial list. That's the gap the automated scanner fills.

The automated route: JS Secrets Scanner

A local grep only covers the code you have checked out. Attackers see what's deployed, including every lazy-loaded chunk. The SecurityInfinity JS Secrets Scanner runs against domains you've verified you own (by DNS TXT record or a matching work email). It analyzes the JavaScript your site serves in production for exposed credentials. Scans are read-only.

It's free to try with the 100 credits included in the Starter plan, on one verified domain, with no card required. If you want continuous re-scans so a bad deploy gets caught the week it ships, the Pro plan ($9/month) runs all agents (recon, web, network, secrets) on a schedule and maps findings to SOC 2, ISO, and OWASP. See pricing for details. Leaked keys often show up next to other exposure, so it's worth also running the Quick Web Scan and Subdomain Takeover checks on the same domain.

Remediation: rotate first, clean up second

When you find a real secret in a bundle, the order of operations matters.

  1. Rotate the key immediately. Assume it has already been collected. Deleting it from code does nothing for copies already scraped, cached by a CDN, or archived by a crawler. In Stripe, for example, rotating a key revokes it and generates a replacement that works right away.
  2. Check usage logs for the old key. Look for requests from IPs, regions, or times you don't recognize. Stripe lets you view API request logs per key. AWS has CloudTrail, and most LLM providers have usage dashboards.
  3. Move the call server-side. If the browser needs the result of a privileged API call, put it behind your own API route or serverless function, add authentication and rate limits, and keep the secret in a server-only env var with no public prefix.
  4. Switch to scoped keys. Use Stripe restricted keys on the server, and add referrer and API restrictions to Google keys. Use the narrowest permissions the provider offers.
  5. Remove source maps from public hosting or block *.map at the CDN.
  6. Clean history last. Rewriting git history is worth doing, but it doesn't help until the key is dead.
  7. Add a guardrail. Run gitleaks or trufflehog in CI on both the repo and the build output, and fail the pipeline on new findings.

Where a scan stops and a pentest starts

A secrets scan tells you a credential is exposed. It doesn't tell you what an attacker could do with that key combined with your access-control model. If you need that answer for a SOC 2 audit or a customer security review, our engineer-delivered pentest reports cover it. External testing is $499 and includes verified findings, evidence, fixes, and a free retest. Authenticated testing is $999 and adds multi-role access-control and business-logic review plus a signed attestation letter.

Start by checking what your production bundles expose today: verify your domain and run a scan. It takes a few minutes. Finding the key yourself is much cheaper than hearing about it from a bug bounty report or a cloud bill.

Frequently asked questions

Is it safe to put API keys in NEXT_PUBLIC_ or VITE_ variables?

Only if the key is designed to be public, like a Stripe publishable key or a properly restricted Firebase web key. Both Next.js and Vite inline these variables into the client bundle at build time, so anyone can read them. Never put secret, admin, or service-role keys behind these prefixes.

Are Firebase API keys a security risk if they're in my JavaScript?

Firebase states that its API keys aren't used to control access to backend data. Firebase Security Rules and App Check do that. The risk comes from weak Security Rules or a key whose API restrictions are too broad, for example one that also allows the Gemini (Generative Language) API. Restrict the key to Firebase APIs and audit your rules.

Can attackers read my source code from source maps?

Yes, if .map files are deployed and publicly reachable. Source maps usually include the original unminified source, including comments and code paths. Next.js and Vite don't generate production browser source maps by default, so check whether your config or error-tracking setup turned them on.

Should I use gitleaks or trufflehog?

Both are free and they overlap a lot. Gitleaks is fast and rule-based, and its dir command scans build folders directly. TruffleHog can verify whether a detected credential is live, which cuts down triage time. Many teams run one in CI and the other as an occasional deep scan.

I removed the leaked key from my code. Am I safe now?

No. Once a key has shipped in a public bundle, assume someone has copied it. Rotate or revoke it with the provider first, then review its usage logs for abuse. Cleaning up code and git history comes after that.

Find what attackers can see, before they do.

AI pentesting agents test your web app, API and cloud, and every finding comes with evidence and a fix. First report in about 10 minutes.

Stay ahead of attackers.

New vulnerabilities, breach write-ups and practical fixes. A few emails a month.