How do you handle environment variables in Next.js?
Assesses fundamental understanding of Next.js conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
Next.js has built-in support for environment variables managed through .env files with strict client/server boundary isolation:
### File Priority Hierarchy:
.env.development.local/.env.production.local(Local overrides, ignored by git).env.local(Always loaded, ignored by git).env.development/.env.production(Environment specific).env(Base defaults)
### Server vs Client Access Rules:
- Server-Only Variables (Default & Secure):
Any variable without a prefix is only accessible in Node.js server runtimes (Server Components, Route Handlers, getServerSideProps):
DATABASE_URL=postgresql://user:secret@localhost:5432/db
STRIPE_SECRET_KEY=sk_live_12345
Attempting to read process.env.STRIPE_SECRET_KEY in browser code returns undefined.
- Client-Exposed Variables (
NEXT_PUBLIC_):
To expose a variable to browser JavaScript bundles, prefix it with NEXT_PUBLIC_:
NEXT_PUBLIC_ANALYTICS_ID=UA-98765432-1
NEXT_PUBLIC_API_URL=https://api.example.com
*Security Warning: Never prefix private database credentials or API secrets with NEXT_PUBLIC_.*
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.