Courses Developer Fundamentals for Builders Environment Security and Deployment Safety

Security for Web Developers

Environment Security and Deployment Safety

Protecting secrets, hardening production, and deploying safely

11 min read · Lesson 12 of 18

Production Is a Different World

Your development environment is permissive by design — verbose errors, no HTTPS, debug mode on. Production must be locked down. The difference between a secure deployment and a vulnerability is configuration.


.env Management

Your .env file contains every secret your application needs: database passwords, API keys, encryption keys. Rules:

  • Never commit .env to git. It's in .gitignore by default. Keep it there.
  • Never echo .env values in logs, error messages, or responses.
  • Use different values per environment. Development, staging, and production should have separate database credentials, API keys, etc.
  • Rotate secrets when team members leave or if a breach is suspected.

On your Forge server, .env is managed through the Forge dashboard or directly on the server. When deploying, the .env file persists across git pull because it's not tracked by git.


Production Hardening Checklist

These settings must be correct in production:

APP_ENV=production
APP_DEBUG=false
APP_URL=https://yourdomain.com
  • APP_DEBUG=false — With debug on, Laravel shows full stack traces with source code, environment variables, and database queries to anyone who triggers an error. This is an instant security breach.
  • APP_ENV=production — Several Laravel features check this: error reporting level, cache behavior, and some packages disable themselves in production.
  • HTTPS everywhere — Set APP_URL to https://. In AppServiceProvider::boot(), add URL::forceScheme('https') if behind a load balancer. Use Let's Encrypt certificates (free, auto-renewing via Forge).

Cache and Optimization

In production, run these commands during deployment:

php artisan config:cache   # Caches config into a single file (faster boot)
php artisan route:cache    # Caches route registrations (faster routing)
php artisan view:cache     # Pre-compiles Blade templates
php artisan optimize       # Runs all three above

These caches mean changes to config files, routes, or Blade templates won't take effect until you re-cache. This is why your deployment script should always run php artisan optimize after pulling new code.

Never run php artisan config:cache on your local machine — it caches the local .env values, and env() calls outside of config files will return null. In development, leave caches uncached.

Key Takeaways

  • Never commit .env and never display debug output in production.
  • APP_DEBUG=false is the most critical production setting.
  • Run php artisan optimize on every deployment for performance and to pick up changes.
  • Use HTTPS everywhere. Let's Encrypt makes this free and automatic.
Ask about this lesson