Security guide
API key found in your JavaScript bundle
When ExposureCheck finds a hardcoded credential in your deployed JavaScript, it means that key is readable by anyone who views your site’s source — not just people who know where to look, but automated scanners, competitors, and anyone who’s curious. This guide walks through what to do first (rotate the key), how the key got into your bundle, and how to fix it permanently.
- Why bundled keys are dangerous
- What ExposureCheck detects
- Rotate the key immediately
- How it got into your bundle
- Move the call server-side
- Prevention checklist
- Verify the fix
- FAQ
Why a key in a JavaScript bundle is dangerous
Your bundled JavaScript is a static file served by your CDN or hosting provider to every visitor. There is no authentication before it’s delivered. The following table shows the realistic impact depending on the type of credential exposed:
| Credential type | What an attacker can do with it | Risk |
|---|---|---|
OpenAI API key (sk-…) |
Run inference against your account; drain your billing limit; access fine-tuned models you’ve trained | Critical |
Stripe secret key (sk_live_…) |
Create or cancel charges, issue refunds, read customer data and payment methods | Critical |
| AWS access key + secret | Read S3 buckets, spin up EC2 instances, exfiltrate secrets from Parameter Store or Secrets Manager | Critical |
| Supabase service role key | Bypass Row Level Security, read and write any table in your database as an admin | Critical |
| SendGrid / Resend send key | Send unlimited email as your domain; damage deliverability reputation; access contact lists | High |
GitHub personal access token (ghp_…) |
Read private repos, push code, delete branches, depending on token scopes | High |
Stripe publishable key (pk_live_…) |
Tokenize card input in a payment form — designed to be public; no server access | Intended public |
| Google Maps / Mapbox public token | Make map tile requests on your behalf; can drain quota if no referrer restriction is set | Medium |
sk- or AKIA finds it in milliseconds regardless of surrounding obfuscation.
What ExposureCheck detects in bundles
ExposureCheck fetches your live JavaScript bundles and applies pattern matching against known credential formats. It looks for:
- OpenAI keys starting with
sk-(alsosk-proj-andsk-org-) - Stripe secret keys (
sk_live_,sk_test_) and publishable keys (pk_live_,pk_test_) - AWS access key IDs starting with
AKIAorASIA - Google API keys starting with
AIza - GitHub tokens starting with
ghp_,gho_, orgithub_pat_ - Supabase service role keys (JWT with
service_rolein the payload) - Generic high-entropy strings assigned to variable names containing
secret,api_key,token, orpassword
For Stripe publishable keys and Google Maps public tokens, ExposureCheck notes the finding but marks them at lower severity — these keys are architecturally intended to be public-facing, though they should still have domain restrictions set.
Step 1: Rotate the exposed key immediately
Before changing any code, revoke the compromised key at the provider. Rotating the key means the old value in your bundle is dead — even if it remains in the code, it can’t be used by anyone who extracts it.
OpenAI
Platform → API keys → find the key → Revoke. Then create a new key. Consider binding the new key to a project to limit scope.
Stripe
Dashboard → Developers → API keys → Roll the secret key. Stripe issues a new secret key while giving you a short window to update running systems before the old one expires.
AWS
IAM → Users → Security credentials → Deactivate the exposed access key. Create a new key pair. Review CloudTrail for any unauthorized API calls made with the old key in the past 30 days.
Supabase
Project Settings → API → Reset the service role JWT secret. Note: this invalidates all existing JWTs for the project, including user sessions. Coordinate the rotation with a redeploy.
GitHub
Settings → Developer settings → Personal access tokens → Delete the exposed token. Create a replacement with the minimum required scopes. Consider a fine-grained token scoped to specific repos.
Google Cloud
Cloud Console → APIs & Services → Credentials → find the key → Delete (or restrict, then create a replacement). Check Cloud Logging → Activity for calls made with the old key.
Step 2: Understand how it got into your bundle
There are three main paths a secret key takes from your local environment into a public JavaScript file:
-
Hardcoded directly in source code The key is written as a string literal in a
.js,.ts, or.jsxfile that gets included in the client bundle. This includes config files, API client initializations, and copy-pasted examples where the placeholder was never replaced. -
Environment variable with a browser-inlining prefix The key is in a
.envfile but prefixed withVITE_,REACT_APP_, orNEXT_PUBLIC_. These prefixes tell the build tool to replace every reference with the literal value at build time — the result is identical to hardcoding the key, and it’s inlined into the compiled bundle as a plain string. -
Imported from a config or constants file The key is defined in a module like
src/config.jsorsrc/constants.tsand imported by components that run in the browser. Even if the file isn’t named something obviously sensitive, if it’s imported by client-side code, its contents go into the bundle.
The common thread: any code that runs in a browser must be treated as public. There is no protected execution context in client-side JavaScript — your bundle is downloaded and executed in a visitor’s browser, and everything in it is readable.
Step 3: Move the API call server-side
The fix is to write a thin server-side route that holds the key as an environment variable and proxies requests from your frontend. The key never leaves the server; your frontend calls your own endpoint instead of the third-party API directly.
The pattern
Before (broken):
Browser → calls third-party API directly using a key in your JS bundle
After (correct):
Browser → calls YOUR server route → server holds the key, calls third-party API
Next.js App Router (route handler)
// app/api/generate/route.ts
// This runs on the server. OPENAI_API_KEY has no NEXT_PUBLIC_ prefix.
import OpenAI from 'openai';
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
export async function POST(request: Request) {
const { prompt } = await request.json();
const completion = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: prompt }],
});
return Response.json({ text: completion.choices[0].message.content });
}
Your frontend calls /api/generate — the OPENAI_API_KEY variable has no NEXT_PUBLIC_ prefix, so it’s never included in the browser bundle.
Vite + Vercel serverless function
// api/generate.ts (Vercel Functions — runs on the server)
import type { VercelRequest, VercelResponse } from '@vercel/node';
export default async function handler(req: VercelRequest, res: VercelResponse) {
// process.env.OPENAI_API_KEY is a server-only env var set in Vercel dashboard
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: req.body.prompt }],
}),
});
const data = await response.json();
res.json({ text: data.choices[0].message.content });
}
Set environment variables correctly
On your hosting platform, add the key as a server-only environment variable:
Vercel
Project Settings → Environment Variables. Add the variable without a VITE_ prefix and ensure it is marked available to Server only — not Browser.
Netlify
Site configuration → Environment variables. Add the key. Reference it in your Netlify Functions via process.env.YOUR_KEY. Do not prefix with NEXT_PUBLIC_ or REACT_APP_.
Cloudflare Workers
Settings → Environment variables → Secrets. Add the key as an encrypted Secret. Available in your Worker via env.MY_KEY, never sent to browsers.
GitHub Actions / self-hosted
Store the key in GitHub Actions Secrets or your server’s environment. Never use env var prefixes that trigger build-time inlining in client bundles.
Prevention checklist
Once the fix is deployed, prevent recurrence:
- Audit all prefixed env vars. Search your codebase for
VITE_,REACT_APP_, andNEXT_PUBLIC_variable names. Any that hold secret keys need to be renamed (remove the prefix) and moved to server-only code paths. - Scan your
.envfiles with LeakCheck before committing. LeakCheck detects credential patterns in your source before they reach your repo or build pipeline. - Add a pre-commit hook. Run a secrets scanner on every commit. See the LeakCheck pre-commit guide for setup with Husky, lint-staged, and git hooks.
- Audit your production bundle after every deploy. Download your production bundle and grep for known key patterns:
grep -r "sk-" dist/,grep -r "AKIA" dist/,grep -r "_live_" dist/. - Disable source maps in production so that even server-side code paths aren’t reconstructible from publicly served files. See the source map fix guide for framework-specific settings.
- Run ExposureCheck after every significant deploy. It scans your live site for exposed keys, env files, source maps, and other credential patterns in one pass.
Verify the fix
1. Run ExposureCheck
ExposureCheck will fetch your live JavaScript, scan for credential patterns, and confirm the key no longer appears in the deployed bundle. If the finding is absent, the fix is confirmed.
2. Check the bundle manually
# Download your main JS bundle and search for key patterns
curl -s https://your-site.com/assets/index.abc123.js | grep -c "sk-"
# Should return 0
curl -s https://your-site.com/assets/index.abc123.js | grep -c "AKIA"
# Should return 0
3. Confirm the API call still works
Test your feature end-to-end with the new key stored server-side. Verify that the server-side route receives and forwards requests correctly and that the third-party API responds as expected. Then run ExposureCheck on staging before deploying to production.
Scan your live site with ExposureCheck to confirm the fix →
Frequently asked questions
Is a hardcoded API key in a JavaScript bundle actually dangerous?
Yes. A key in your deployed JavaScript is readable by anyone who opens browser developer tools, by automated security scanners, and by web crawlers. The minified bundle is a public static file — anyone who visits your site can download it and search for credential patterns. There is no runtime protection that prevents extraction once a value is embedded in client-side code. If the key has any write permissions, billing implications, or rate limits, treat it as compromised immediately.
What kinds of keys does ExposureCheck find in bundles?
ExposureCheck scans for well-known credential patterns: OpenAI keys (sk-…), Stripe keys (sk_live_, sk_test_, pk_live_), AWS access key IDs (AKIA…), Google API keys (AIza…), GitHub tokens (ghp_, gho_, github_pat_), Supabase service role JWTs, and generic high-entropy strings in variables named secret, api_key, or token. Stripe publishable keys and Google Maps public tokens are flagged at lower severity — architecturally intended to be public, but should still have domain restrictions configured.
I found an API key in my bundle — what should I do first?
Rotate (revoke and replace) the exposed key at your provider’s dashboard before touching any code. Assume it has already been seen — many credential-harvesting attacks are silent. Once the old key is revoked, it’s dead even while it remains in your deployed bundle. Then follow this guide to fix the code so the new key never ends up in the bundle, and run ExposureCheck to confirm the fix.
How did an API key end up in my JavaScript bundle?
The three most common root causes: (1) Hardcoded directly in a source file included in the client bundle. (2) In a .env file prefixed with VITE_, REACT_APP_, or NEXT_PUBLIC_ — these prefixes tell the build tool to inline the value into the browser bundle at build time, making it identical to hardcoding. (3) Imported from a config file that gets included in client-side code. Any code that runs in a browser is public.
What’s the right way to call an API requiring a secret key from a web app?
Write a server-side proxy route that holds the key as a server-only environment variable and forwards requests from your frontend. In Next.js, use an App Router route handler in app/api/. In Vite-based apps on Vercel or Netlify, use a serverless function. The frontend calls your own endpoint, your endpoint calls the third-party API with the key, and the key is never included in anything the browser downloads.
Can I obfuscate or base64-encode the key in my bundle instead?
No. Base64 decodes in one command. JavaScript obfuscators make code harder to read in general but do not protect specific known-format strings — an attacker searching for sk- or AKIA will find the encoded value and decode it. Any key embedded in client-side JavaScript, regardless of encoding, should be treated as publicly visible. The only real fix is moving the key to server-side code that never runs in a browser.
How do I make sure the new key never ends up in the bundle?
Three steps: (1) Store the new key as a server-only environment variable with no client-inlining prefix. (2) Scan your .env files with LeakCheck before every commit. (3) After deploying, run ExposureCheck on your live site to confirm the key is absent from the bundle. Also disable source maps so that server-side code paths aren’t reconstructible from the deployed assets.
Related guides in the ExposureCheck suite
Disable source maps in Vite, Next.js and webpack so your original source isn’t reconstructible from the bundle.
Critical fix Fix an exposed .env fileRotate credentials, block the path on every hosting platform, and verify the fix across Nginx, Apache, Vercel, and Netlify.
Pre-commit LeakCheckScan your source code and .env files for hardcoded API keys before they reach your repo or your bundle.