🔧 Error Fixes
· 2 min read

Environment Variable Not Found / Undefined — How to Fix It


Error: Missing required environment variable: DATABASE_URL
TypeError: Cannot read properties of undefined (reading 'split')
KeyError: 'API_KEY'

Your code expects an environment variable that isn’t set. It’s either missing from your .env file, not loaded, or not passed to the runtime.

Fix 1: .env File Not Loaded

// ❌ Node.js doesn't load .env files automatically
console.log(process.env.API_KEY);  // undefined

// ✅ Install and configure dotenv
npm install dotenv
require('dotenv').config();  // Add at the top of your entry file
console.log(process.env.API_KEY);  // Works
# Python
pip install python-dotenv
from dotenv import load_dotenv
load_dotenv()
import os
print(os.getenv('API_KEY'))

Fix 2: .env File in Wrong Location

# ❌ .env is in a subdirectory
src/.env  # dotenv looks in the project root by default

# ✅ Put .env in the project root (next to package.json)
mv src/.env .env

Fix 3: Variable Name Mismatch

# ❌ .env has a different name than your code expects
# .env
DB_URL=postgresql://localhost/mydb

# code
process.env.DATABASE_URL  # undefined — wrong name!

# ✅ Match the names exactly (case-sensitive)

Fix 4: Spaces Around the Equals Sign

# ❌ Spaces break .env parsing
API_KEY = sk-12345  # Parsed as " sk-12345" with leading space

# ✅ No spaces
API_KEY=sk-12345

Fix 5: Docker — Not Passed to Container

# ❌ .env exists on host but not in container
docker run myapp  # No env vars

# ✅ Pass env file
docker run --env-file .env myapp

# Or pass individually
docker run -e API_KEY=sk-12345 myapp
# docker-compose.yml
services:
  app:
    env_file: .env
    # Or inline:
    environment:
      - API_KEY=sk-12345

Fix 6: Vite/Next.js — Wrong Prefix

# ❌ Client-side code can't access server env vars
# Vite: must prefix with VITE_
VITE_API_URL=https://api.example.com  # ✅ Accessible in browser
API_SECRET=secret123                   # ❌ Not accessible in browser

# Next.js: must prefix with NEXT_PUBLIC_
NEXT_PUBLIC_API_URL=https://api.example.com  # ✅

Debugging

# Check if the variable is set
echo $API_KEY
printenv | grep API

# Node.js
node -e "console.log(process.env.API_KEY)"

# Python
python3 -c "import os; print(os.environ.get('API_KEY', 'NOT SET'))"