Next.js Course
Next.js
/
Beginner

Environment Variables

Definition

Values that are dynamically injected into the application at runtime or build time, keeping sensitive secrets (like API keys and Database passwords) completely out of the source code.

Explain Like I'm New

You NEVER type your Database Password directly into `db.ts`. If you commit it to GitHub, hackers will find it and delete your database in 5 minutes. Instead, you put it in a `.env` file, which is explicitly ignored by GitHub.

Real World Example

Using a `.env.development` file on your laptop to connect to a local dummy database, and using Vercel's dashboard to set the Production environment variables to connect to the real database.

Common Use Cases

  • Secret management
  • Different environments (Dev vs Prod)
  • Configuration

Interactive Example

/* 
  .env file contents: 
  DATABASE_PASSWORD="super-secret-123"
  NEXT_PUBLIC_ANALYTICS_ID="UA-98765432-1"
*/

// 1. In a Server Component (or API Route):
export default async function ServerPage() {
  // ✅ SAFE: This runs on the Node server. It has full access.
  const password = process.env.DATABASE_PASSWORD;
  return <div>Server</div>;
}

// 2. In a Client Component ('use client'):
'use client';
export default function ClientPage() {
  // ✅ WORKS: The variable has the NEXT_PUBLIC prefix.
  const analyticsId = process.env.NEXT_PUBLIC_ANALYTICS_ID;
  
  // ❌ FAILS: Returns 'undefined'. Next.js protects secrets!
  const password = process.env.DATABASE_PASSWORD; 
  
  return <div>Client</div>;
}

Interview Questions

basic

  • What prefix MUST you add to an environment variable in Next.js if you want it to be exposed to the browser (Client Components)?

intermediate

  • If a variable is named `DATABASE_URL` (without the prefix), can a Client Component read it?

Flash Cards

Question

What prefix?

Click to reveal answer
Answer

`NEXT_PUBLIC_` (e.g., `NEXT_PUBLIC_STRIPE_KEY`).

Question

Client read without prefix?

Click to reveal answer
Answer

No. Next.js heavily protects standard environment variables. If it doesn't have the prefix, it is completely stripped from the client bundle. It will return `undefined` in the browser.