🎓 A1Learner
🔍
0 of 50 lessons completed

Next.js Environment Variables

.env.local holds secrets on your computer. Only names that start with NEXT_PUBLIC_ reach the browser.

The two lines in .env.local

The secret line holds the real key. The public line holds the app name. Never share the file.

BOOKSHELF_SECRET=sk-your-secret-here
NEXT_PUBLIC_BOOKSHELF_NAME=My Bookshelf

The secret is not in the browser code

The check reads the secret from the file, then greps the build. Zero client files hold it. One built page file does.

SECRET=$(grep "^BOOKSHELF_SECRET=" .env.local | cut -d= -f2)
grep -r -l "$SECRET" .next/static | wc -l
grep -r -l "$SECRET" .next/server/app

Example

curl -s http://localhost:3110/env | grep -o "Server sees the secret: <!-- -->yes"
curl -s http://localhost:3110/env | grep -o "App name in the browser: <!-- -->My Bookshelf"

Key points

  • .env.local holds two lines. One is the secret, and one is the public name.
  • The server reads the secret. The page shows "Server sees the secret: yes".
  • The browser reads the public name. The page shows "App name in the browser: My Bookshelf".
  • The secret is absent from the browser JavaScript. Zero files under .next/static hold it.
  • The secret sits in the built page file. The build drew the client part on the server, with the real value.
  • A client component must never read a secret. The server draw puts it in the served page.

In this example, two checks read the served env page. The server line says yes, so the server sees the secret. The browser line shows the app name, so the browser sees the public name. The browser never sees the secret in its JavaScript. But the secret still sits in the built page file, because the build drew the page on the server. The rule is simple: a secret stays on the server, and a client component never reads one.

Note

A secret in .env.local stays off Git. Never commit the file.

Try it Yourself

Edit the code, then press Run.

Running is simulated · TypeScript Playground

Exercise

Where does the secret leak in this app?