Next.jsEasy
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 destructuringconst { NEXT_PUBLIC_X } = process.envstaysundefinedin 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
taintoption plus React'sexperimental_taintUniqueValuecan 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// .env2// NEXT_PUBLIC_SITE_NAME="DevQnA"3// STRIPE_SECRET_KEY="sk_live_..."45// app/components/footer.tsx6"use client";78export function Footer() {9 // Works: replaced with "DevQnA" at build time10 const name = process.env.NEXT_PUBLIC_SITE_NAME;1112 // undefined in the browser: not prefixed, never shipped13 const secret = process.env.STRIPE_SECRET_KEY;1415 // Does NOT work: dynamic lookup is not inlined16 const key = "NEXT_PUBLIC_SITE_NAME";17 const dynamic = process.env[key];1819 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.