Next.js Medium technical 1 views 1 min read

How do you handle environment variables in Next.js?

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of Next.js conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

Next.js has built-in support for environment variables managed through .env files with strict client/server boundary isolation:

### File Priority Hierarchy:

  1. .env.development.local / .env.production.local (Local overrides, ignored by git)
  2. .env.local (Always loaded, ignored by git)
  3. .env.development / .env.production (Environment specific)
  4. .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

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?