Skip to content

Next.js NEXT_PUBLIC_ variables: never put secrets in them

Guide/ 12 min read

NEXT_PUBLIC_ copies the value into the browser's JavaScript at build time. What that looks like in the bundle, what can be public and how to rotate a leaked key.

  • Next.js
  • Security
In this article (8)
  1. What the NEXT_PUBLIC_ prefix does
  2. What an exposed key looks like in the browser
  3. What can be public
  4. Where secrets go: Route Handlers, Server Actions and Server Components
  5. If it already leaked: how to rotate the key
  6. Common mistakes
  7. Frequently asked questions
  8. Checklist

A NEXT_PUBLIC_ variable in Next.js is copied as plain text into the JavaScript the browser downloads when you run next build. Anyone who opens your site can read it. So it is only for public values, like a GA4 measurement ID; secret keys get no prefix and are used in server code only.

Below you will see what an exposed key looks like in the bundle (we tested it on a demo app with Next 15.5.23 and fake values), what can be public, where secrets belong and what to do if one already leaked. If you are deciding which components go to the browser, start with where to put 'use client' in Next.js; and if your API takes calls from the browser, also read why CORS does not protect your API.

What the NEXT_PUBLIC_ prefix does

By default, Next.js environment variables only exist on the server, in the Node.js environment. Per the Next.js environment variables guide, the NEXT_PUBLIC_ prefix tells Next.js to "inline" the value: during next build it replaces every process.env.NEXT_PUBLIC_... with the literal value, and that value ends up in any JavaScript sent to the browser. It is not a runtime lookup. It is text copied into your files.

The demo app has this .env.local (the values are fake on purpose):

NEXT_PUBLIC_STORE_NAME=Tienda Demo
NEXT_PUBLIC_PAYMENTS_SECRET_KEY=sk_test_FALSO_PUBLICO_123
PAYMENTS_SECRET_KEY=sk_test_FALSO_SERVIDOR_456
PAYMENTS_API_URL=http://localhost:3200/api/fake-provider
  1. NEXT_PUBLIC_STORE_NAME is genuinely public: the store name is already on the page.
  2. NEXT_PUBLIC_PAYMENTS_SECRET_KEY is the mistake this article is about: a secret key with the public prefix. (FALSO is Spanish for fake.)
  3. PAYMENTS_SECRET_KEY is the same key done right: no prefix, server only.
  4. PAYMENTS_API_URL points at a fake payments provider that runs inside the demo itself.
from .env.local to the browser, in one next build.env.localNEXT_PUBLIC_PAYMENTS_SECRET_KEY=sk_test_FALSO_PUBLICO_123PAYMENTS_SECRET_KEY=sk_test_FALSO_SERVIDOR_456next buildinlinesbrowser.next/static/chunkssk_test_FALSO_PUBLICO_123visible in DevToolsserverprocess.env at runtimePAYMENTS_SECRET_KEYnot in .next/staticwhat ended up in the chunkAuthorization:"Bearer ".concat("sk_test_FALSO_PUBLICO_123")minified, still plain textNEXT_PUBLIC_ is copied into the JS at buildwithout the prefix it stays on the server, unless you hand it to a client component

Scroll the figure sideways to see all of it

The value is frozen at build time

The guide warns about it: after the build, your app no longer responds to changes in those variables. If you build one Docker image and promote it through several environments, every NEXT_PUBLIC_ variable keeps its build-time value. We checked it with this page, which reads one variable of each kind after connection():

import { connection } from "next/server";

export default async function RuntimePage() {
  await connection();
  return (
    <ul>
      <li id="public">{process.env.NEXT_PUBLIC_STORE_NAME}</li>
      <li id="server">{process.env.STORE_REGION}</li>
    </ul>
  );
}
  1. await connection() makes the page render on every request instead of at build time. It is what the guide recommends for reading variables at runtime.
  2. We built with NEXT_PUBLIC_STORE_NAME=Tienda Demo and STORE_REGION=centro.
  3. Without rebuilding, we changed .env.local to Tienda Cambiada and norte and restarted next start.
  4. Result: the page showed Tienda Demo and norte. The public variable kept its build value, on the server too; the server variable picked up the new one.

Dynamic lookups are not a safeguard

The guide says dynamic lookups, such as process.env[varName] or const env = process.env followed by env.NEXT_PUBLIC_..., are not inlined. We tried all three in a client component, and this is what happened in our build:

How the client component reads itValue found in .next/static?Value in the browser
process.env.NEXT_PUBLIC_STORE_NAMEYesThe value
process.env.PAYMENTS_SECRET_KEY (no prefix)Noundefined
const env = process.env; then env.NEXT_PUBLIC_DYNAMIC_ONLYYes, on Next 15.5.23The value
process.env[name] with a constant nameNoundefined
A read(key) helper returning process.env[key]Noundefined

The third row contradicts the docs: with const env = process.env, the value did end up in the chunk. That is not a rule, just what we measured on this version, and the practical takeaway is the same either way: do not use dynamic lookups to hide a value or to read one at runtime. Treat every NEXT_PUBLIC_ variable as public. As for unprefixed variables, the Server and Client Components guide says Next.js replaces them with an empty string; in our build they became a read from an empty object and came out as undefined. Either way, the value does not arrive.

What an exposed key looks like in the browser

Here is the classic mistake: calling the payments provider straight from a client component, with the secret key in a public variable.

"use client";

export default function BadPayButton() {
  async function pay() {
    await fetch("https://api.payments.example/v1/sessions", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.NEXT_PUBLIC_PAYMENTS_SECRET_KEY}` },
    });
  }
  return <button type="button" onClick={pay}>Pay</button>;
}
  1. "use client": this file and its imports ship to the browser.
  2. pay() calls the provider's API from the shopper's browser.
  3. The Authorization header carries process.env.NEXT_PUBLIC_PAYMENTS_SECRET_KEY. It works, and that is exactly the problem: to work, the key has to be in the browser.

After next build, we searched the folder that gets served to browsers for both values:

$ grep -rl "sk_test_FALSO_PUBLICO_123" .next/static
.next/static/chunks/app/bad/page-78203093a6f45326.js
$ grep -rl "sk_test_FALSO_SERVIDOR_456" .next/static
$ grep -o "Authorization:[^}]*" .next/static/chunks/app/bad/page-*.js
Authorization:"Bearer ".concat("sk_test_FALSO_PUBLICO_123")
  1. The prefixed key is in the chunk for the /bad page, a file served from /_next/static/.
  2. The unprefixed key is in no file under .next/static.
  3. The minified fragment leaves the key in plain text. Minifying is not encrypting.

Nobody needs your source code to find it: open the browser's developer tools and search the JavaScript files the page loaded, or download the chunk from the URL in the HTML. If a key is in NEXT_PUBLIC_, it is already public.

No prefix can still leak

Dropping the prefix is not enough if the value reaches the browser some other way. We found two in the demo. The first: passing the secret as a prop to a client component.

import PaymentsWidget from "@/components/PaymentsWidget";

export default function LeakPage() {
  return <PaymentsWidget apiKey={process.env.PAYMENTS_SECRET_KEY} />;
}

PaymentsWidget does not even render the key; it just shows "ready" when there is one. Even so, a client component's props travel serialized in the RSC payload, inside the HTML:

$ grep -o 'apiKey[^,]*' .next/server/app/leak.html
apiKey\":\"sk_test_FALSO_SERVIDOR_456\"}]

The second: reading process.env.PAYMENTS_SECRET_KEY inside a 'use client' component and rendering it. In the browser it is undefined, but the component is also prerendered on the server, where the variable exists, and the value was written into the page's HTML:

$ grep -o 'id="secret">[^<]*' .next/server/app/probe.html
id="secret">sk_test_FALSO_SERVIDOR_456

The rule both tests point to: a secret must not touch any 'use client' file, neither as a process.env read nor as a prop.

What can be public

A public variable is one you would not mind seeing published tomorrow. The quick test: if it leaked, would you have to rotate it? If yes, it gets no prefix.

what can take the prefix and what never canwhat it isexample nameNEXT_PUBLIC_?store nameNEXT_PUBLIC_STORE_NAMEyesGA4 measurement IDNEXT_PUBLIC_GA_IDyespayments publishable keyNEXT_PUBLIC_PAYMENTS_KEYyespayments secret keyPAYMENTS_SECRET_KEYnever · serverdatabase URLDATABASE_URLnever · serveradmin API tokenSHOP_ADMIN_TOKENnever · serverwebhook signing secretWEBHOOK_SECRETnever · serverif a leak means rotating it, it gets no prefixpublic means anyone who opens your site can read it

Scroll the figure sideways to see all of it

  • Fine to make public: your store name, the public URL of your site or API, a GA4 or Google Tag Manager ID, and keys the provider calls "publishable" or client-side, which are meant to be used in the browser.
  • Never: payment secret keys, database URLs with a username and password, admin API tokens (Shopify Admin, your CMS, your ERP), secrets used to sign webhooks or sessions, and keys for pay-per-use services such as AI or email APIs.

A publishable key is not a key without limits: if your provider lets you restrict it by domain or by permission, do it.

Where secrets go: Route Handlers, Server Actions and Server Components

The safe shape is that the browser never talks to the provider with your key: it talks to your server, and your server talks to the provider. In the demo, all access to the key lives in one module, lib/payments.js:

import "server-only";

export async function createSession() {
  const res = await fetch(`${process.env.PAYMENTS_API_URL}/sessions`, {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.PAYMENTS_SECRET_KEY}` },
  });
  if (!res.ok) throw new Error(`payments: ${res.status}`);
  return res.json();
}

export async function getAccountStatus() {
  const res = await fetch(`${process.env.PAYMENTS_API_URL}/status`, {
    headers: { Authorization: `Bearer ${process.env.PAYMENTS_SECRET_KEY}` },
  });
  if (!res.ok) throw new Error(`payments: ${res.status}`);
  return res.json();
}
  1. import "server-only" turns any import of this module from a client component into a build error. We tried it: the build failed with "You're importing a component that needs "server-only"".
  2. createSession() reads the URL and the key from process.env on the server, at runtime.
  3. If the provider answers with an error, it throws with the status code, never with the key.
  4. getAccountStatus() uses the same key for a read; same pattern.

Route Handler. For calls that arrive over HTTP, such as a mobile app or another service of yours, app/api/checkout/route.js:

import { createSession } from "@/lib/payments";

export async function POST() {
  const session = await createSession();
  return Response.json({ id: session.id });
}

It returns only the session id, not the provider's whole response: whatever leaves the handler reaches the browser. In the demo, POST /api/checkout answered {"id":"cs_test_FALSO_001"}.

Server Action. To call it from your own UI without writing an endpoint, app/checkout/actions.js:

"use server";

import { createSession } from "@/lib/payments";

export async function startCheckout() {
  const session = await createSession();
  return { id: session.id };
}

The button is a client component that receives the action as a prop and never sees the key:

"use client";

import { useState } from "react";

export default function PayButton({ action, children }) {
  const [id, setId] = useState(null);
  return (
    <>
      <button type="button" onClick={async () => setId((await action()).id)}>
        {children}
      </button>
      {id && <p role="status">{id}</p>}
    </>
  );
}

Server Component. The page ties it together: it reads data with the key on the server and hands the action to the button, app/checkout/page.jsx:

import { connection } from "next/server";
import { getAccountStatus } from "@/lib/payments";
import { startCheckout } from "@/app/checkout/actions";
import PayButton from "@/components/PayButton";

export default async function CheckoutPage() {
  await connection();
  const status = await getAccountStatus();
  return (
    <main>
      <p>{process.env.NEXT_PUBLIC_STORE_NAME} · {status.mode}</p>
      <PayButton action={startCheckout}>Pay</PayButton>
    </main>
  );
}
  1. await connection() renders the page on every request, so it reads the key at runtime.
  2. getAccountStatus() runs on the server; the page only receives status.mode.
  3. startCheckout is passed as a prop. Server Actions can be passed to client components; regular functions cannot.
  4. On click, the browser showed cs_test_FALSO_001. We checked the HTML and every JavaScript file the page loaded: the server key was in none of them.

If it already leaked: how to rotate the key

If a secret key sat in a NEXT_PUBLIC_ variable and reached production, treat it as compromised. Removing the prefix does not invalidate it: the old JavaScript lives on in caches, CDNs and copies someone already downloaded. These are the steps, in order:

  1. Create a new key in the provider's dashboard. If you can limit its permissions to what your server uses, do it.
  2. Store it without the prefix in your host's environment variables, and move the code that uses it to the server (a Route Handler, a Server Action or a server-only module).
  3. Build and deploy. The old value was inlined at build time, so only a new build takes it out of the JavaScript you serve. Then search .next/static for the old key to confirm.
  4. Revoke or delete the old key at the provider. This is the step that actually closes the leak.
  5. Check the provider's logs and activity since the day the key reached production (your git and deploy history tell you when): charges, refunds or data reads you do not recognize.
  6. If the key ever made it into a commit, it stays public even after you delete the file. You have rotated it; now make sure your .env files are in .gitignore. The Next.js guide warns you almost never want to commit them.
rotating a leaked key, in ordercreate newat the providerno prefixserver onlybuild + deployJS without itrevoke oldnow invalidcheck logsuse since leakorder mattersrevoke before deploying andpayments fail until the deploy;if the leak is serious, revoke nowand accept a few minutes of errorswhy revokeold JS lives on in caches and CDNsand in copies someone already saved;a new deploy does not invalidate it,only the provider cana key that reached the browser is already publicdropping the prefix without rotating leaves the old key working

Scroll the figure sideways to see all of it

If the key moves money or customer data and is already exposed, do not wait for the deploy: revoke it first and accept a few minutes of checkout errors. A broken checkout is fixed by a deploy; a key someone else is using is not.

Common mistakes

  • Adding the prefix "so it works on the client". If the browser needs the key to work, the design is wrong: move the call to the server.
  • Assuming minified or obfuscated is safe. In the chunk, the key is still plain text.
  • Reading a secret in a 'use client' component. In the browser it is undefined, but if you render it, the server prerender writes it into the HTML.
  • Passing the secret as a prop. A client component's props travel in the payload, even if you never display them.
  • Returning the provider's full response from a Route Handler or a Server Action. What you return reaches the browser; return only what you need.
  • Changing the variable on your host without rebuilding. NEXT_PUBLIC_ variables keep their build-time value.
  • Dropping the prefix without rotating. The old key still works for whoever copied it.

Frequently asked questions

Can I hide the key by splitting it up or encoding it in base64?

No. The browser has to put it back together to use it, so anyone reading the JavaScript can too. If the browser needs it, it is not a secret.

Can a variable without NEXT_PUBLIC_ reach the browser?

Yes: if you pass it as a prop to a client component, render it in one, or return it from a Route Handler or a Server Action. We reproduced the first two in the demo.

Why did I change the variable on my host and the site still shows the old value?

Because NEXT_PUBLIC_ variables are inlined during next build. You have to rebuild and redeploy for them to change.

How do I read a per-environment value in the browser without rebuilding?

The Next.js guide suggests exposing it through your own API, or reading it on the server during dynamic rendering and passing it down as a prop. Only do that with public values.

Checklist

  • No NEXT_PUBLIC_ variable holds a secret key, a token or a password.
  • After a build, you searched .next/static for the first characters of your secret keys and they are not there.
  • Modules that use secrets start with import "server-only".
  • No 'use client' file reads a secret from process.env or receives one as a prop.
  • Route Handlers and Server Actions return only the data the UI needs.
  • Your .env files are in .gitignore.
  • If a key was exposed, you rotated it, revoked it and checked the provider's logs.

The NEXT_PUBLIC_ prefix is not a permission, it is a publication: whatever carries it, anyone can read. To decide which parts of your page are client code, continue with where to put 'use client' in Next.js; to protect the API your browser calls, read why CORS does not protect your API. And if you work with an AI agent in the repo, a hook that protects your .env keeps it from reading the file by accident.

Saw this on Instagram? Comment SECRETOS on the Reel and I'll send you the guide.

Written by

Luis Morales

Luis Morales

Frontend and Shopify developer, EcomLabs

@luismoralesdev on Instagram

Published October 30, 2026 · updated November 1, 2026

← Blog