A developer adds the NEXT_PUBLIC_ prefix to an environment variable so it is "easy to call from a component", builds, deploys, and a partner's API key now sits in a JavaScript file anyone can download. Exploiting this takes no skill: open the Network tab, grab the chunk, search for a string. This guide shows how to check for a Next.js API key leak and set up three layers that keep it from happening again. It applies to Next.js 16 with the App Router, checked against the official Data Security guide (last updated 18 November 2026).

Why the NEXT_PUBLIC_ prefix turns a secret into public data

According to the Next.js docs, environment variables are available only on the server by default. Add the NEXT_PUBLIC_ prefix and, during next build, the framework replaces every process.env.NEXT_PUBLIC_... reference with the real value and inlines it into the JavaScript sent to the browser.

Two consequences are worth remembering:

  • The value is frozen at build time. If you build one Docker image and promote it across environments, every NEXT_PUBLIC_ variable carries the value from the build environment.
  • Deleting the variable from .env after deployment undoes nothing. The old build still contains the key, so treat that key as compromised.

The rule is simple: use this prefix only for values meant to be public, such as an analytics ID or a public maps key. Secret keys, database connection strings and internal tokens never get it.

Checking the bundle: look for the key in the build output

Do not rely on "it's probably not there". Scan the build output, because that is what outsiders see. The JavaScript delivered to browsers lives in .next/static.

# 1. Build exactly as you do for deployment
npm run build

# 2. Look for suspicious names and patterns in browser-facing files
grep -rIn -E "(secret|private[_-]?key|api[_-]?key|password|token)" .next/static | head -n 50

# 3. Check one specific value (keep it in a shell variable, not in command history)
grep -rIlF "$VALUE_TO_CHECK" .next/static && echo "FOUND IN BUNDLE"

The second command is noisy because third-party libraries use these words too, so read each hit in context. The third is precise: if a real secret turns up, you have your answer. Run it against staging first, then add it to your CI pipeline so every build is scanned.

For Docker images, inspect the layer that contains the build output, not just the source. The story of an API key exposed in a Docker Hub image and exploited within 8 seconds shows how short the gap between exposure and abuse can be.

Layer one: keep data-access modules server-only

The Next.js docs recommend a Data Access Layer for new projects: an internal library that runs only on the server, performs authorization checks and returns minimal data. The server-only package turns that convention into a real build error.

// data/user-dto.ts
import 'server-only'

const apiKey = process.env.PARTNER_API_KEY // no NEXT_PUBLIC_ prefix

export async function getPartnerStatus(orderId: string) {
  const res = await fetch(`https://api.example.com/orders/${orderId}`, {
    headers: { Authorization: `Bearer ${apiKey}` },
  })
  const data = await res.json()
  // Return only what the UI needs
  return { status: data.status }
}

If someone imports this file from a Client Component ('use client'), the build fails instead of quietly bundling it. The docs also advise letting only the data-access layer read process.env, so the rest of the app never touches secrets.

Layer two: pass Client Components only what they display

Keys are not the only thing that leaks. Personal data often escapes differently: a Server Component loads a whole user row and hands the object to a Client Component. Every field, including phone numbers or internal IDs, ends up in the data sent to the browser.

// Avoid: passing the whole userData object
return <Profile user={userData} />

// Prefer: filter in the data layer and return public fields only
const publicProfile = await getUser(slug) // returns { name }
return <Profile user={publicProfile} />

In code review, treat a Client Component's props as a public contract. If the prop type is wider than what the UI renders, narrow it. For personal data, also mask or anonymise it before it leaves the server; see Besoft's AI Masking solution.

Layer three: React Taint as a safety net

Next.js supports React's taint APIs to mark an object or value as not allowed to reach the client. The feature is still experimental and must be enabled in the config:

// next.config.js
module.exports = {
  experimental: {
    taint: true,
  },
}

The docs stress that this is an additional layer only. You still need to filter data in the data-access layer before it enters React's render context. Because it is experimental, trial it on a separate branch and watch for changes between versions.

If it already leaked: rotate first, clean up later

When the scan finds a real key, order matters more than polish:

  1. Revoke the key and issue a new one at the provider. Do not wait for the code fix.
  2. Review the old key's usage logs for unfamiliar access.
  3. Move the call into a route handler or Server Action so the key stays on the server.
  4. Rebuild, redeploy and rerun the scans above.
  5. Add the scan to CI so the next mistake is caught early.

Recent cases show leaked keys get abused quickly, as in the API key leak in AI agent logs. If you are also updating Next.js, read our roundup of 2026 Next.js advisories and the guide to CSP and nonce configuration for another line of defence in the browser.

Common mistakes

  • Adding NEXT_PUBLIC_ to "make it work locally" and never reverting it.
  • Assuming that changing an environment variable on the server updates the bundle. The value was inlined at build time.
  • Importing a server-only module into a 'use client' file and "fixing" the build error by removing the package instead of splitting the logic.
  • Using select * and passing the whole row down to a component.

If your team wants to audit a running Next.js app, start with the three scan commands above on a staging build. The output will show right away what needs fixing first.

References