What is the NEXT_PUBLIC prefix used for in environment variables?

NEXT_PUBLIC_ marks an environment variable as safe for the browser. At next build, Next.js replaces every process.env.NEXT_PUBLIC_X reference in client code with its literal value. Variables without the prefix stay on the server only.

How the inlining works

process.env.NEXT_PUBLIC_ANALYTICS_ID is a text replacement at build time, not a runtime lookup. That has consequences:

  • The value is frozen into the JavaScript bundle. Changing it in your hosting dashboard has no effect until you rebuild.
  • Dynamic lookups are not replaced. process.env[name] or destructuring const { NEXT_PUBLIC_X } = process.env stays undefined in the browser.
  • Anything with the prefix is public. Anyone can read it in the bundle, so never prefix secrets.

What happens without the prefix

In a Client Component, process.env.SECRET_KEY is undefined. This is a security feature: server secrets cannot leak by accident.

Patterns

  • Same build, many environments. Read a non-prefixed variable on the server at request time (after await connection()), then pass the value to Client Components as a prop.
  • Keep secrets server-side. Call third-party APIs from Route Handlers or Server Functions instead of exposing keys.
  • Taint. The experimental taint option plus React's experimental_taintUniqueValue can block secret values from ever being passed to the client.

Interview point

Explain both halves: the prefix controls exposure, and inlining means build time, not run time.

Code example

tsx
1// .env
2// NEXT_PUBLIC_SITE_NAME="DevQnA"
3// STRIPE_SECRET_KEY="sk_live_..."
4
5// app/components/footer.tsx
6"use client";
7
8export function Footer() {
9 // Works: replaced with "DevQnA" at build time
10 const name = process.env.NEXT_PUBLIC_SITE_NAME;
11
12 // undefined in the browser: not prefixed, never shipped
13 const secret = process.env.STRIPE_SECRET_KEY;
14
15 // Does NOT work: dynamic lookup is not inlined
16 const key = "NEXT_PUBLIC_SITE_NAME";
17 const dynamic = process.env[key];
18
19 return (
20 <footer>
21 © {name} {secret === undefined && dynamic === undefined ? "(safe)" : ""}
22 </footer>
23 );
24}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app