guide9 min readBy Aliniyaz Mamat · updated

What is NEXT_PUBLIC_ in Next.js env variables?

NEXT_PUBLIC_ environment variables are the only variables Next.js copies into the browser: at next build, every literal process.env.NEXT_PUBLIC_* in client code is replaced with its value. Everything else stays on the server. Getting this wrong either leaks a secret to every visitor or leaves you reading undefined in a component.

Key takeaways

  • ✓No prefix = server only. NEXT_PUBLIC_ = inlined into the JavaScript bundle and readable by anyone.
  • ✓Values are baked in at build time: changing them in your host's dashboard does nothing until you rebuild.
  • ✓Only literal references are inlined: process.env[name] and copies of process.env give undefined in the browser.
  • ✓In Docker, the value must exist during next build (build arg), not only when the container starts.
  • ✓Publishable, anon and analytics keys may be public; secret keys, service-role keys and database URLs never.

Server-only by default

.env.local
DATABASE_URL=postgres://…                 # server only
STRIPE_SECRET_KEY=sk_test_…               # server only
NEXT_PUBLIC_SITE_URL=https://myapp.com    # browser + server
NEXT_PUBLIC_STRIPE_PK=pk_test_…           # browser + server

This default means DATABASE_URL or OPENAI_API_KEY can't reach the browser just because a shared module mentions them. In a client component they are simply undefined; Next.js doesn't warn.

How the build inlines NEXT_PUBLIC_ values

During next build, Next.js performs a text replacement in client code: process.env.NEXT_PUBLIC_FOO becomes the string value. Two consequences follow:

  • A new value needs a rebuild. The production bundle is frozen; redeploy after changing a public variable (even a no-op deploy works).
  • Dynamic access doesn't work. Only the exact text is replaced:
const name = "NEXT_PUBLIC_ANALYTICS_ID";
process.env[name];                     // ❌ not inlined → undefined in the browser

const env = process.env;
env.NEXT_PUBLIC_ANALYTICS_ID;          // ❌ not inlined

process.env.NEXT_PUBLIC_ANALYTICS_ID;  // ✅ inlined

A common version of this bug is a helper like getEnv("NEXT_PUBLIC_API_URL") that works on the server and silently returns undefined in client components.

Which .env file wins in Next.js

  1. process.env: variables already set in the shell or by the host
  2. .env.$(NODE_ENV).local, e.g. .env.production.local
  3. .env.local (skipped when NODE_ENV=test)
  4. .env.$(NODE_ENV), e.g. .env.production
  5. .env

Next.js stops at the first match. Keep .env*.local out of git and commit a template made with the .env.example generator.

NEXT_PUBLIC_ in Docker and CI

Dockerfile
ARG NEXT_PUBLIC_API_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
RUN npm run build

# docker build --build-arg NEXT_PUBLIC_API_URL=https://api.example.com -t myapp .

Setting the variable only when the container starts has no effect on the client bundle. Build args end up in the image metadata, which is fine for public values and exactly why secrets must never be NEXT_PUBLIC_. Vercel passes project variables to the build automatically; on Docker-based hosts, mark the variable as available at build time.

What may be public and what never

VariableTypical valueOK in the browser?
NEXT_PUBLIC_SITE_URLhttps://myapp.comyes
NEXT_PUBLIC_API_URLhttps://api.myapp.comyes, URLs are public
NEXT_PUBLIC_SUPABASE_URL + …_ANON_KEYproject URL + anon keyyes, Row Level Security protects data
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEYpk_live_…yes, built for browsers
NEXT_PUBLIC_POSTHOG_KEY, NEXT_PUBLIC_GA_IDanalytics IDsyes
NEXT_PUBLIC_CAPTCHA_SITE_KEYTurnstile/hCaptcha/reCAPTCHA site keyyes; the secret key stays server-side
database URLs, sk_…, service-role keys, OAuth client secrets, JWT secrets, AI API keys—never

Not sure about a value? The ENV leak checker flags known secret formats; any hit with a NEXT_PUBLIC_ prefix must be renamed and rotated.

Common mistakes

"use client";
const url = process.env.API_URL;              // ❌ undefined in the browser
const url2 = process.env.NEXT_PUBLIC_API_URL; // ✅
# ❌ ships the secret key to every visitor
NEXT_PUBLIC_STRIPE_SECRET_KEY=sk_live_…
  • Updating a public value in the host dashboard and expecting the live site to change without a redeploy.
  • Reading env in a client component instead of a server component that passes values down as props.

A safe pattern: two validated env modules

// lib/env.ts (server only)
import { z } from "zod";
export const env = z.object({
  DATABASE_URL: z.string().url(),
  STRIPE_SECRET_KEY: z.string().startsWith("sk_"),
}).parse(process.env);

// lib/env.client.ts (public values, referenced literally so they get inlined)
export const publicEnv = z.object({
  NEXT_PUBLIC_SITE_URL: z.string().url(),
  NEXT_PUBLIC_STRIPE_PK: z.string().startsWith("pk_"),
}).parse({
  NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,
  NEXT_PUBLIC_STRIPE_PK: process.env.NEXT_PUBLIC_STRIPE_PK,
});

Note the explicit object for the client schema: passing process.env as a whole would not be inlined in the browser.

Different values per environment without rebuilding

If one Docker image is promoted from staging to production, don't use NEXT_PUBLIC_ for values that differ. Read them on the server at request time and pass them to the client:

app/(dashboard)/layout.tsx
import { connection } from "next/server";
import { ClientConfig } from "@/components/client-config"; // your own context provider

export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
  await connection(); // render per request, so env is read at runtime
  return <ClientConfig apiUrl={process.env.API_URL!}>{children}</ClientConfig>;
}

This makes everything below the layout dynamic, so use the smallest layout that needs the value. Related: NEXT_PUBLIC_ vs VITE_, Vercel environment variables, Next.js .env generator.

Frequently asked questions

Why is my NEXT_PUBLIC_ variable still undefined?

It's inlined at build time. Restart next dev after adding it, rebuild after deploying, and reference it literally as process.env.NEXT_PUBLIC_NAME.

Can I expose NEXT_PUBLIC_SUPABASE_ANON_KEY safely?

Yes, the anon key is meant to be public; Row Level Security protects your data. The service-role key must stay server-only.

Does NEXT_PUBLIC_ work in server components?

Yes, public variables work everywhere. Non-prefixed variables only exist on the server.

How do I check which values ended up in my build?

Search the client output after next build, e.g. grep -r "https://api.example.com" .next/static, or look in the browser's Sources tab. If a secret shows up there, rotate it.

Do Vercel system variables need the NEXT_PUBLIC_ prefix?

To read them in the browser, yes. Enable "Automatically expose System Environment Variables" and use the prefixed names, e.g. NEXT_PUBLIC_VERCEL_ENV.

Related tools

Continue reading