Environment Variables
6 min read
Managing Secrets and Configuration
Next.js reads .env.local for local development. Variables are available in server-side code via process.env.VARIABLE_NAME. To expose a variable to the browser, prefix it with NEXT_PUBLIC_ — but never put secrets in NEXT_PUBLIC_ variables, as they are embedded in the client bundle.
text
# .env.local
DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
SENDGRID_API_KEY=SG.xxxxxx
NEXT_PUBLIC_SITE_URL=http://localhost:3000
NEXT_PUBLIC_GA_ID=G-XXXXXXXXXXts
// Server-side only (safe for secrets)
const db = new PrismaClient();
const apiKey = process.env.SENDGRID_API_KEY;
// Client-side safe (public, non-secret)
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL;Add .env.local to your .gitignore. Commit a .env.local.example file with placeholder values so other developers know which variables to set.
Ready to test yourself?
Practice Next.js— quiz & coding exercises