Environment Variables Best Practices

matt
Matthew Gros · Oct 28, 2025

TLDR

Never commit secrets, use .env files locally, environment variables in production, validate required vars on startup.

Environment Variables Best Practices

Secrets Don't Belong in Code

One leaked API key can cost thousands.

The .env File

APP_NAME=MyApp
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_DATABASE=myapp
DB_USERNAME=root
DB_PASSWORD=secret

STRIPE_SECRET=sk_test_xxx

Never Commit Secrets

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

Provide .env.example without real values:

STRIPE_SECRET=your-stripe-key-here

Access in Code

// Laravel
$key = env('STRIPE_SECRET');
$key = config('services.stripe.secret'); // Better

// Node.js
require('dotenv').config();
const key = process.env.STRIPE_SECRET;

Validate on Startup

// AppServiceProvider boot()
$required = ['STRIPE_SECRET', 'DB_PASSWORD'];
foreach ($required as $var) {
    if (empty(env($var))) {
        throw new \Exception("Missing required env var: {$var}");
    }
}

Production Environments

Don't use .env files in production. Use:

  • Platform env vars: Heroku, Vercel, Forge
  • Secrets managers: AWS Secrets Manager, Vault
  • Container env: Docker, Kubernetes secrets

Best Practices

  1. Different values per environment - never share prod creds with dev
  2. Rotate secrets regularly - especially after team changes
  3. Least privilege - only grant permissions needed
  4. Audit access - know who can see what

About the Author

matt

I build and ship automation-driven products using Laravel and modern frontend stacks (Vue/React), with a focus on scalability, measurable outcomes, and tight user experience. I’m based in Toronto, have 13+ years in PHP, and I also hold a pilot’s license. I enjoy working on new tech projects and generally exploring new technology.