Bundle security
How to prevent secrets from ending up in your JavaScript bundle
Vite, Create React App, and Next.js all inject prefixed environment variables into your compiled bundle at build time — it’s a feature, not a bug. The problem arises when a secret key picks up one of those prefixes and ships to every visitor as a plain string embedded in your JavaScript. Here is how the mechanism works, how to audit for leaks, and how to architect around it.
- How it happens
- The three dangerous prefixes
- What belongs in the bundle
- How to audit for leaks
- The server proxy fix
- Prevention checklist
- FAQ
How secrets end up in the bundle
Modern JavaScript bundlers solve a real problem: your source code uses environment variables for configuration, but the browser has no concept of a process environment. The bundler bridges this gap by reading variable values at build time and substituting the literal string directly into the compiled output.
So when Vite compiles this line:
const res = await fetch(url, {
headers: { Authorization: `Bearer ${import.meta.env.VITE_OPENAI_KEY}` }
});
The compiled bundle contains something like this:
const res = await fetch(url, {
headers: { Authorization: "Bearer sk-proj-abcXYZ..." }
});
The key is now a literal string in a file served to the public. Browser devtools, a grep on the bundle, or a linked source map makes it trivially readable. There is no runtime protection that prevents extraction once a value is embedded this way.
The three dangerous prefixes
Each major bundler or framework exposes a different subset of environment variables to the browser. Variables that do not carry the prefix are server-side only and will be undefined in the compiled browser bundle.
VITE_ variable server-side.
| Framework | Client-side prefix | Access pattern | Server-only (no prefix) |
|---|---|---|---|
| Vite (React, Vue, Svelte…) | VITE_ |
import.meta.env.VITE_* |
Any var without VITE_ |
| Create React App | REACT_APP_ |
process.env.REACT_APP_* |
Any var without REACT_APP_ |
| Next.js | NEXT_PUBLIC_ |
process.env.NEXT_PUBLIC_* |
Any var without NEXT_PUBLIC_ |
| SvelteKit | $env/static/public |
import { VAR } from '$env/static/public' |
$env/static/private, $env/dynamic/private |
What belongs in the bundle and what doesn’t
Not all API keys are secrets. Some are explicitly designed to be public:
-
Safe
Stripe publishable key (
pk_live_...)Stripe’s publishable key is intentionally public. It can only tokenise payment details — it cannot charge a card, create a customer, or read transaction history. Those operations require the secret key (
sk_live_...), which must never reach the browser. -
Safe
Mapbox public token, Google Maps API key (with referrer restrictions)
These are designed for client-side use. Protect them with HTTP referrer restrictions in the provider’s dashboard, not by hiding them from the browser.
-
Verify
Firebase config object (
apiKey,authDomain)Firebase’s client config is technically a project identifier, not a secret. Security is enforced through Firestore Security Rules and Firebase Auth, not by keeping the config private. Confirm your security rules are restrictive before treating this as safe.
-
Never
OpenAI API key (
sk-proj-.../sk-...)A leaked OpenAI key gives anyone full access to your account’s billing and quota. Use a server-side proxy instead. See the code examples below.
-
Never
Stripe secret key, Supabase service role key, database URLs, AWS credentials
Any credential that grants write access, elevated permissions, or unbounded read access to a data store must never appear in a client-side bundle.
The test: would the API provider be surprised to see this value in a public GitHub repository? If yes, it belongs on the server.
How to audit your bundle for exposed secrets
Three complementary approaches, ordered from fastest to most thorough:
-
Scan source files before you build with LeakCheck
Before committing or pushing, paste your
.envfile and any config modules into LeakCheck. It runs entirely in your browser and flags patterns matching API keys from OpenAI, Stripe, AWS, Supabase, and dozens of other providers. Catching a misplaced secret here — before it reaches the bundle — means no git history to rewrite and no deployed leak to roll back. -
Grep your built output locally
After running
npm run build, search the compiled output for known key patterns:# OpenAI keys grep -r "sk-" dist/ --include="*.js" # AWS access keys grep -r "AKIA" dist/ --include="*.js" # Verify no prefix strings leaked through (should return nothing) grep -r "VITE_" dist/ --include="*.js" grep -r "REACT_APP_" dist/ --include="*.js" grep -r "NEXT_PUBLIC_" dist/ --include="*.js"The last three greps should find nothing in a correctly configured build — prefix strings are replaced with their values at compile time, leaving no trace of the prefix itself. Any match suggests a misconfigured bundler or a secret that was inlined as a string literal before the build step.
-
Scan your live URL with ExposureCheck
After deploying, run ExposureCheck against your live domain. It fetches your JavaScript bundle and any linked source maps, scans for API key patterns in the compiled output, and flags publicly accessible
.js.mapfiles. Source maps are the amplifier: a leaked key is extractable from a minified bundle, but a source map makes your entire application logic readable in browser devtools.
The server proxy pattern: keeping secrets on the server
When your frontend needs to call an API that requires a secret key, write a server-side route that acts as a proxy. The frontend calls your route; your server calls the third-party API with the secret; your server returns only what the frontend needs. The secret never leaves your server’s process environment.
Next.js App Router
// app/api/generate/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function POST(req: NextRequest) {
const { prompt } = await req.json();
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// OPENAI_API_KEY has no NEXT_PUBLIC_ prefix — server-side only
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: prompt }],
}),
});
const data = await response.json();
return NextResponse.json({ content: data.choices[0].message.content });
}
Vite project on Vercel (serverless function)
// api/generate.ts (repo root — Vercel auto-detects /api directory)
import type { VercelRequest, VercelResponse } from '@vercel/node';
export default async function handler(req: VercelRequest, res: VercelResponse) {
const { prompt } = req.body;
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Set OPENAI_API_KEY in Vercel dashboard — no VITE_ prefix
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: prompt }],
}),
});
const data = await response.json();
res.json({ content: data.choices[0].message.content });
}
Then in your Vite frontend, call /api/generate instead of OpenAI directly. No VITE_ prefix. No secret in the bundle.
Prevention checklist
-
Audit every prefixed variable in your
.envGo through each
VITE_,REACT_APP_, andNEXT_PUBLIC_variable. Ask: would the API provider be surprised to see this value in a public GitHub repo? If yes, remove the prefix and move the usage to a server-side route. -
Run LeakCheck on your
.envbefore committingPaste
.env,.env.local, and.env.productioninto LeakCheck before your first commit and whenever you add new variables. -
Disable source maps in production builds
Source maps make bundle analysis trivial. Set
build.sourcemap: falsein yourvite.config.ts,devtool: falsein your webpack production config, orproductionBrowserSourceMaps: falseinnext.config.js. This reduces the attack surface but does not remove a secret already in the bundle — fix the root cause with a server proxy. -
Write server-side routes for any API call requiring a secret
The proxy pattern above works for any framework. The secret lives in an environment variable without the client-side prefix; the browser only talks to your own routes; your routes talk to third-party APIs.
-
Scan your live deployment with ExposureCheck after each significant config change
Run ExposureCheck after changing your build config, switching hosting providers, or adding a new subdomain — each can silently re-enable source maps or expose assets that were previously protected.
Frequently asked questions
Which environment variables end up in my JavaScript bundle?
It depends on your bundler. Vite exposes VITE_* via import.meta.env.VITE_*. Create React App exposes REACT_APP_* via process.env.REACT_APP_*. Next.js exposes NEXT_PUBLIC_* via process.env.NEXT_PUBLIC_*. All other variables are server-side only and will be undefined in the browser build. The rule: if you access it in client-side code via import.meta.env or process.env, it is in the bundle.
Can someone actually extract an API key from my bundle?
Yes, easily. Bundlers inject values as literal strings. Anyone who visits your site can open browser devtools, go to the Sources tab, and search for the key string. If source maps are enabled — the default in many configurations — the un-minified source is fully readable. There is no practical obfuscation that prevents extraction once a value is embedded in the bundle.
Is it ever safe to put an API key in VITE_ or NEXT_PUBLIC_?
Yes — when the key is explicitly designed to be public: Stripe publishable keys (pk_live_...), Mapbox public tokens, Google Maps API keys with referrer restrictions. These are designed for client-side use. The test: would the API provider be surprised to see this value in a public GitHub repo? If yes, it belongs on the server.
My app needs to call OpenAI from the frontend. What’s the right approach?
Write a server-side API route. Your frontend calls your own route (e.g., /api/generate), your server calls OpenAI with the key stored in an environment variable without a NEXT_PUBLIC_ prefix, and your server returns the result. See the server proxy examples above.
How do I check if my current live site has secrets in the bundle?
Run ExposureCheck on your live URL — it probes for accessible source map files and scans compiled JavaScript for API key patterns. You can also audit locally: run npm run build, then grep -r "sk-" dist/ for OpenAI-style keys or grep -r "AKIA" dist/ for AWS. For pre-commit source scans, use LeakCheck.
Does disabling source maps fix a bundle leak?
No. Disabling source maps makes the leak harder to find but does not remove the secret. The literal string value is still in the minified JavaScript — a determined person can still search for it in devtools or by fetching the bundle file directly. The fix is to move the secret to a server-side route, not to obscure the bundle.
Does LeakCheck scan compiled bundle files?
LeakCheck is optimised for source code: paste your .env files, config modules, or individual source files before building. For scanning your deployed site’s compiled bundle and source maps, use ExposureCheck — it fetches the live URL and scans the served assets directly.
The full Copper Bay Labs ship-safety suite
Run all six tools before you flip a new project live. Each covers a distinct failure mode; none overlaps with the others.
Paste code or a .env file and see every exposed API key and secret flagged by severity. Runs entirely in your browser.
Scan your live URL for exposed .env files, .git directories, source maps, and bundled secrets.
Check your live site’s security headers: CSP, HSTS, X-Frame-Options, Referrer-Policy, and more.
Dependencies DepCheckPaste your package.json to find packages with CVEs, abandoned maintainers, or typosquatting risk.
Plain-English ADA/WCAG accessibility and privacy risk report for any live URL. Flags the issues that attract demand letters.