Topic 38 of 39
Environment Variables
Overview
Next.js has built-in support for .env files. By default, all environment variables are securely hidden on the server. If you need a variable to be accessible in the browser (Client Components), you must prefix it with NEXT_PUBLIC_.
Syntax
bash
# .env.local
DATABASE_URL="postgres://user:pass@localhost:5432/db" # Server only
NEXT_PUBLIC_API_URL="https://api.public.com" # Client & Server
// Accessing in code
const dbUrl = process.env.DATABASE_URL;
const apiUrl = process.env.NEXT_PUBLIC_API_URL;Common Pitfalls
- Prefixing sensitive keys (like Stripe Secret Keys) with
NEXT_PUBLIC_, accidentally leaking them to the browser bundle. - Expecting
process.envto be fully dynamic at runtime in Client Components. Next.js hardcodesNEXT_PUBLIC_variables during the build process.
Interview Questions
Q:
What is the difference between
.env.development and .env.local?A:
.env.development is committed to version control and contains default dev values. .env.local overrides all other files, is strictly for local secrets, and should ALWAYS be added to .gitignore.
Real-World Example
Keeping API keys secure while allowing front-end API URLs to be configured.
example
bash
// In a Server Component (Safe)
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
// In a Client Component (Safe)
const fetchURL = process.env.NEXT_PUBLIC_FRONTEND_URL;Check Your Knowledge
Test your understanding of Environment Variables with these quick questions.