Environment Variables Not Loaded

Fix issues with environment variables not being recognized.

Environment Variables Not Loaded

Configuration values showing as undefined or empty? Your environment variables might not be loading correctly.

Symptoms

Error: OPENAI_API_KEY is not defined

or

TypeError: Cannot read property of undefined

or bot starts but can't connect to services.

Likely Causes

  1. .env file in wrong location
  2. Syntax error in .env file
  3. Docker not loading env file
  4. Variable name typo
  5. Quotes around values causing issues

Fix Steps

1. Check .env File Location

The .env file must be in the same directory as docker-compose.yml:

ls -la
# Should show both:
# -rw-r--r--  .env
# -rw-r--r--  docker-compose.yml

2. Check .env Syntax

Common mistakes:

# WRONG - spaces around equals
OPENAI_API_KEY = sk-xxx

# WRONG - extra quotes for simple values
OPENAI_API_KEY="sk-xxx"

# CORRECT
OPENAI_API_KEY=sk-xxx

# CORRECT - quotes needed for values with spaces
APP_NAME="My Moltbot Instance"

Validate your file:

# Check for hidden characters
cat -A .env

# Should show lines ending in $ (newline)
# Watch for ^M (Windows line endings) - fix with:
sed -i 's/\r$//' .env

3. Check Docker Compose Configuration

# docker-compose.yml
services:
  moltbot:
    env_file:
      - .env  # This line must exist

Or verify variables are passed:

docker-compose config  # Shows resolved configuration

4. Verify Variables Are Loaded

# Check inside container
docker exec moltbot env | grep OPENAI

# Check specific variable
docker exec moltbot printenv OPENAI_API_KEY

5. Check Variable Names

Ensure names match exactly what Moltbot expects:

# List expected variables
docker exec moltbot cat /app/.env.example

# Compare with your .env
diff .env.example .env

Verify

After fixing, restart and verify:

docker-compose down
docker-compose up -d
docker exec moltbot env | grep -E "(API_KEY|TOKEN|URL)"

Common Mistakes

Editing .env without restart: Changes to .env require docker-compose restart to take effect.

Copying from docs with hidden characters: Copy-paste from websites can include invisible characters. Type values manually if having issues.

Using env_file in wrong section: Must be directly under the service, not under environment:.