Next.js loads environment variables from .env* files. Names prefixed with NEXT_PUBLIC_ are exposed to the browser; everything else stays server-only.
Common files
.env # defaults
.env.local # local overrides (gitignored)
.env.production # production build
Usage
const dbUrl = process.env.DATABASE_URL; // server only
const apiBase = process.env.NEXT_PUBLIC_API_BASE; // available client-side
Rules
- Never prefix secrets with
NEXT_PUBLIC_ - Access env vars at build time for static optimization where possible
- Document required vars in README and deployment dashboard
next.config.js
Configure redirects, image domains, experimental flags, and bundler options—keep secrets out of config files committed to git.
Self-check
- Which prefix exposes a variable to the client bundle?
- Where should
DATABASE_URLlive?
Pitfall: Never prefix API keys or DB URLs with NEXT_PUBLIC_—that inlines them into client JavaScript.
Interview prep
- NEXT_PUBLIC_ rule?
Only prefix vars safe to expose in the browser bundle; secrets like DATABASE_URL stay unprefixed and server-only.