
Editorial illustration; the code and review scene represent a security workflow, not a real repository.
You open a newly deployed site, hit DevTools or View Source, and spot a familiar string inside the compiled JavaScript bundle: an API key. It might be buried inside minified vendor code or assigned to an obscure variable name, but none of that matters—the browser has already downloaded it. Anyone who can load the page can copy that key and replay it from curl or Postman outside your app.
That is the non-negotiable rule of frontend development: anything the browser executes or receives is public. Minification, base64 encoding, hidden <input> fields, or build-time .env tricks do not change where the trust boundary sits.
Why the browser is an untrusted client
On a backend server—whether ASP.NET Core, Node.js, or PHP—an environment variable stays in process memory and never leaves your host. A browser application works the opposite way. To render your page, the server hands over HTML, CSS, JavaScript bundles, source maps, and API responses directly to the visitor’s machine.
Even for a small site or side project, an exposed secret is a real liability. Someone can burn through your paid OpenAI, SMS, or map-geocoding quota overnight, read private records, or use a low-privilege token to probe what else your backend exposes. Users inspecting your network requests is normal web behaviour; the mistake is handing an untrusted client a credential that belongs on a server.
How secrets sneak into frontend bundles
The obvious leak is hardcoding a key directly in client-side JavaScript:
// Never do this in browser code
const apiKey = "sk_live_example";
fetch("https://api.example.com/private", {
headers: { Authorization: `Bearer ${apiKey}` }
});
More often, leaks happen quietly through build tools. A developer puts API_SECRET=... into .env (which is rightly ignored by .gitignore), and then prefixes it with VITE_ or NEXT_PUBLIC_ so the frontend code can read import.meta.env.VITE_API_SECRET. Because .env is not in Git, it feels safe—yet Vite or Next.js literally bakes that string into the static JavaScript bundle during npm run build.
Other leaks slip in through debugging leftovers: an API endpoint that echoes upstream headers in an error payload, a console.log(config) left behind in production, public .js.map source maps exposing older code, or a secret that was deleted in the latest commit but still sits in Git history.
Publishable keys vs. secret keys
Not every key in browser code is a bug. Services like Stripe (pk_live_...), Cloudflare Turnstile site keys, or Google Maps browser keys are designed to live in client-side JavaScript. What makes them safe is not their variable name—naming something PUBLIC_API_KEY proves nothing—but how the provider scopes them.
A genuinely public key is safe only when the provider documents it as client-facing and you lock down its restrictions: HTTP referrer / allowed origin rules (e.g., *.yourdomain.com/*), restricted API scopes, and strict billing quotas or alerts. Anything that grants write access, admin privileges, or unrestricted billing should never touch the browser.
Move trust to a server endpoint
When your frontend needs data from a private third-party API, put a thin server-side proxy in front of it—an ASP.NET Core Minimal API endpoint, a Next.js Route Handler, or a Cloudflare Worker. The browser sends only the user’s input; the server validates the session and input, reads the secret from its runtime environment (or dotnet user-secrets locally), calls the upstream API, and returns a filtered response.
// Browser calls your own endpoint—no upstream key in sight
const res = await fetch("/api/report?id=42", {
method: "GET",
credentials: "include"
});
On the server (for example, a Cloudflare Worker or backend route), the secret stays out of reach:
export default {
async fetch(request, env) {
// Validate session / input first, then use env.REPORT_API_KEY
const upstream = await fetch("https://api.example.com/reports/42", {
headers: { Authorization: `Bearer ${env.REPORT_API_KEY}` }
});
const data = await upstream.json();
return Response.json({ summary: data.summary });
}
};
A server endpoint still needs proper authentication, authorization, input validation, and rate limiting, but it keeps the upstream credential on the side of the architecture that can actually protect it.
Pre-release checks that catch leaks early
Before shipping a build, run a quick check against both your source tree and the compiled output. A fast search over dist/ or .next/ takes two seconds and catches build-time VITE_ or NEXT_PUBLIC_ mistakes that source-only linters miss:
# Search the built frontend bundle for common key prefixes or env leaks
rg -n "sk_live_|AIza|ghp_|Bearer |API_SECRET|PRIVATE_KEY" dist/
Pair that with a local secret scanner like gitleaks in a pre-commit hook so credentials never enter Git history in the first place. Do not paste suspected keys into random online web tools to “check” them.
Next, load the production build in a clean Incognito window with the DevTools Network tab open. Watch every XHR/fetch request during login, form submission, and error states. Check query strings, Authorization headers, JSON response bodies, and whether .map files are publicly served. Finally, keep a short inventory of every credential in the project—which service it belongs to, what scope it has, and who owns rotation—so test keys created during prototyping do not quietly ride into production.
If a secret has already shipped
If you discover a live private key in a deployed bundle or public Git commit, treat it as compromised immediately—even if billing looks normal today:
- Rotate or revoke the key at the provider first. Do not wait to finish a full root-cause write-up before invalidating an exposed live credential.
- Audit usage logs and billing for unexpected requests, newly created resources, or quota spikes.
- Find every copy—check CI/CD variables, staging configs, error logs, screenshots, and cached CDN bundles.
- Replace the frontend call with a server-side endpoint or a properly restricted public key.
- Purge or rewrite Git history only after rotating—removing a line in a new commit leaves the old value readable in
git log -p, though rotation is what actually neutralizes the key.
Keep the rule simple
The easiest way to avoid frontend credential leaks is to stop relying on memory about which framework prefix is public and which is private. Assume that anything shipped to the browser—every string in dist/, every header, and every JSON field—is readable by anyone on the internet. Keep private credentials on the server, restrict public keys to specific origins and quotas, and verify the compiled bundle before you deploy.
For related engineering checklists, see It Works in Your Terminal: How to Make Commands Reliable Everywhere Else and Your Bug Report Is Not a Conversation: How to Give Developers a Repro They Can Use.