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'))"
Related resources
Related: Python Cheat Sheet Β· Pip Install Error Fix Β· Docker Cheat Sheet Β· Docker vs Kubernetes