πŸ“ Tutorials
Β· 2 min read
Last updated on

What are Environment Variables? A Simple Explanation for Developers


Environment variables are key-value pairs that live outside your code and configure how your application behaves. Instead of hardcoding a database URL or API key in your source code, you store it as an environment variable and read it at runtime.

This is one of the most fundamental concepts in software development β€” and one of the first things that trips up beginners when deploying to production.

Why use environment variables?

Three reasons:

  1. Security β€” secrets (API keys, database passwords) don’t belong in your code. If your code is on GitHub, anyone can see them. Environment variables keep secrets out of version control.

  2. Configuration per environment β€” your local database URL is different from staging, which is different from production. Environment variables let you use the same code with different configs.

  3. The Twelve-Factor App β€” this is an industry-standard methodology that says config should be stored in the environment, not in code. Every major platform (Vercel, AWS, Heroku, Docker) follows this pattern.

How to use them

In your terminal

# Set a variable
export DATABASE_URL="postgres://localhost:5432/mydb"

# Read it
echo $DATABASE_URL

# Use it in a command
node server.js  # your code reads process.env.DATABASE_URL

In a .env file

Most projects use a .env file for local development:

# .env
DATABASE_URL=postgres://localhost:5432/mydb
API_KEY=sk-abc123
PORT=3000

Then load it in your code. In Node.js:

// Automatically loaded by most frameworks (Next.js, Vite, Astro)
// Or manually with dotenv:
import 'dotenv/config';

const db = new Database(process.env.DATABASE_URL);
const port = process.env.PORT || 3000;

In Python:

import os
from dotenv import load_dotenv

load_dotenv()
db_url = os.getenv("DATABASE_URL")

Critical rule: never commit .env files

Add .env to your .gitignore:

# .gitignore
.env
.env.local
.env.*.local

Instead, create a .env.example file with placeholder values and commit that:

# .env.example (committed β€” shows what variables are needed)
DATABASE_URL=postgres://localhost:5432/mydb
API_KEY=your-api-key-here
PORT=3000

Environment variables in production

Every hosting platform has a way to set environment variables:

  • Vercel β€” Settings β†’ Environment Variables
  • Docker β€” ENV in Dockerfile or -e flag: docker run -e DATABASE_URL=... myapp
  • GitHub Actions β€” repository secrets and env: in workflow files
  • AWS β€” Parameter Store, Secrets Manager, or ECS task definitions

Common mistakes

  • Committing .env to Git (use .gitignore)
  • Using different variable names locally vs production
  • Forgetting to set variables in CI/CD (builds fail with β€œundefined”)
  • Prefixing issues β€” in Next.js, only NEXT_PUBLIC_* variables are exposed to the browser

Learn more

Related: AI Security Checklist