ALL POSTS

API Key Exposed in JavaScript? Find and Fix the Leak

November 9, 2026 · 6 min read

secretsjavascript
A glowing key revealed among abstract layers of blurred code bars.

An API key exposed in JavaScript is visible to anyone who can load that JavaScript. The browser must receive the code it executes, so renaming variables, minifying a bundle, or hiding a settings screen cannot create a private boundary. The important questions are what the key authorizes, whether it belongs in a browser, and how to contain it if it does not.

This guide explains frontend API key security using your own source code and build artifacts. It also distinguishes public identifiers from credentials that authorize privileged operations. That distinction prevents both missed leaks and unnecessary panic over legitimate client configuration.

How keys get into browser bundles

A developer adds a provider SDK, needs a credential, and exposes an environment variable so the client component can read it. The build succeeds, the feature works, and the credential becomes part of a downloadable asset. Environment files are useful configuration storage; they are not automatically a security boundary.

In Next.js, variables prefixed with NEXT_PUBLIC_ can be inlined into browser code at build time. The resulting value is not changed merely by editing an environment variable after the bundle was built. See the Next.js environment variable guide.

Vite similarly exposes variables with its public prefix, normally VITE_, to client code. Treat those values as public and inspect custom prefix configuration too. The Vite documentation describes this behavior. Server-looking filenames or comments do not override what the build actually includes.

Public key or secret credential?

Start with the issuing service’s documentation and the credential’s permissions, not a scanner’s pattern match alone.

Example Intended browser use What to verify
Stripe publishable key Yes, for supported client integrations Correct environment and server-side payment authorization
Stripe secret or restricted server key No Scope, account access, rotation, affected usage
Firebase web configuration Usually public configuration Authentication, Security Rules, restrictions, quotas
Cloud access-key pair Not as a long-lived embedded secret Permissions, storage access, billing exposure
Privileged AI service key No Server-only use, authentication, quotas and budget controls

Stripe’s key documentation distinguishes publishable and secret credentials. Firebase’s API-key guidance explains why Firebase client configuration is not the same as access authorization. A public Firebase key does not excuse permissive database rules, and restrictions still deserve review.

Inspect your own output, not just source files

Build the production application locally and search the assets intended for browsers. Use file-only output first so a potential secret does not appear in terminal logs:

npm run build

# Next.js browser assets; adjust paths for your project.
rg -l --glob '*.js' 'sk_live_|AKIA|PRIVATE KEY|secret[_-]?key' .next/static

# A typical Vite output directory.
rg -l --glob '*.js' 'sk_live_|AKIA|PRIVATE KEY|secret[_-]?key' dist

This is a limited heuristic, not a complete secret scanner. It can miss credentials with unfamiliar formats and match harmless examples. Inspect candidate files locally, determine the issuer and permissions, and redact the value before sharing evidence. Never “test” an unknown credential against somebody else’s account.

Also review HTML, JSON configuration endpoints, source maps, service workers, and any files copied into the public directory. Use browser developer tools to confirm which artifact is really delivered to production users. A clean development bundle says little about a different production build.

Source maps security: useful debugging data, not the main boundary

Source maps can expose original source, paths, and comments that make a bundle easier to understand. They may also contain values already present in the compiled output. Removing a map does not remove a credential from the JavaScript itself.

Choose deliberately whether browser source maps should be public. If your monitoring service accepts private uploads, keep access controlled and ensure deployment does not publish the same map files. Recheck after build-tool changes. The separate configuration exposure guide explains why HTTP status alone is not enough to establish that a file is genuinely being served.

Put privileged calls behind a protected server boundary

The browser should call a narrowly defined operation in your application. Your server verifies the user, checks permission for that operation, validates input, enforces limits, and only then calls the provider with a server-side credential.

A Next.js server-only configuration module can make accidental client imports fail early:

// src/lib/provider-config.ts
import 'server-only';

export function requireProviderKey(): string {
  const key = process.env.PROVIDER_API_KEY;
  if (!key) throw new Error('Provider integration is not configured');
  return key;
}

Keep this module out of client components and public API responses. Do not rename the variable to NEXT_PUBLIC_PROVIDER_API_KEY to fix a browser error. That would remove the boundary you are trying to create.

A safe request path looks like this:

Browser -> your authenticated endpoint
        -> user and resource authorization
        -> input validation + per-user limits
        -> fixed provider operation with server credential
        -> minimal response, without provider credentials

This diagram is an implementation contract, not a complete authentication example. Use your existing session middleware and permission model. An unauthenticated server proxy can still let strangers spend your provider budget even though the key itself stays hidden.

Avoid turning the proxy into a new vulnerability

Do not accept an arbitrary upstream URL from the browser. Fix the provider host and allowed operation server-side, cap payload sizes, set timeouts, and validate any returned data you persist. Authorize resource ownership before forwarding a user-supplied identifier.

For cookie-authenticated state changes, maintain CSRF defenses. Apply rate limits by user as well as a suitable network signal, and set account-level usage controls with the provider where available. Error messages should help the user recover without returning request headers, internal configuration, or complete upstream error objects.

Rotate a leaked key and verify the rollout

If a privileged key was publicly delivered, removing it from the next build is only one step. Determine its permissions and affected account, inspect usage, and create a replacement using the provider’s rotation procedure. Update legitimate consumers, verify they work, and revoke the old credential promptly.

Review CDN caches, old deployment URLs, downloadable archives, and repository history. You may be able to remove copies, but cannot assume every copy disappeared. Revocation is what makes a known old credential stop authorizing requests. Document the incident using a redacted identifier, owner, date, and evidence that the previous key is disabled.

Prevent the same mistake next month

Add secret scanning to pull requests and build artifacts, separate public and private configuration, and assign an owner to every external integration. Review key permissions when a feature changes. During code review, ask what prevents an unauthenticated visitor from invoking the server-side operation, not only where the key is stored.

Check your own site — your first scan is free. Scanwise combines passive intelligence with non-destructive external checks and can flag suspicious client-side patterns with AI-assisted fix suggestions. Findings need review: a public identifier is not automatically a secret, and a clean scan cannot prove every credential is safe. Starter credits require a verified account and are subject to anti-abuse limits.

Check your own site

Run the same external recon on your own domain. First scan is free.

RUN AI SCAN — FIRST SCAN FREE