Course outline · 0% complete

0/29 lessons0%

Course overview →

Environment variables done right

lesson 9-1 · ~10 min · 27/29

Quiz

Warm-up from 'CSS in Next.js': what makes a styles.card class from a *.module.css file collision-proof?

Secrets and settings

You met .env files and process.env in Backend with Node.js, and the rule carries over: config lives in environment variables, never in code. Next.js reads .env.local automatically:

DATABASE_URL=postgres://…
STRIPE_SECRET_KEY=sk_live_…
NEXT_PUBLIC_ANALYTICS_ID=abc123

The twist: a Next.js app runs in two places at once — some code on the server, some in the browser — and a variable readable by browser code is readable by every visitor, not just you. So Next.js needs to know, per variable, which side may see it, and it decides by a naming rule:

  • Plain names (DATABASE_URL) are server-only. Server components, actions, and route handlers can read them. They never reach the browser.
  • Names starting with NEXT_PUBLIC_ are inlined into the browser bundle at build time. Anyone can read them in DevTools, so only genuinely public values belong here.

Code exercise · javascript

Build the exposure audit you would run before a deploy (pure JavaScript, runnable here). Write publicEnvNames(names): given an array of environment variable names, return only the ones Next.js will inline into the browser bundle — the ones starting with "NEXT_PUBLIC_". Print each on its own line. If a secret ever shows up in this list, it is about to be readable by every visitor.

Quiz

A client component reads process.env.STRIPE_SECRET_KEY and gets undefined, while a server action reads it fine. Why?

Problem

True or false: renaming STRIPE_SECRET_KEY to NEXT_PUBLIC_STRIPE_SECRET_KEY is a safe way to fix the undefined value in a client component.