Dev Basics · 4 min read
Environment Variables: .env Best Practices
Environment variables are how applications get configuration — database URLs, API keys, feature flags — without hard-coding it. The .env file is the local convention for supplying them.
This guide covers how they work and the practices that keep secrets out of your repository.
Try it yourself with the related tool.
Convert .env and JSON →Advertisement
Why configuration lives outside code
The same codebase runs in development, staging, and production, each needing different settings. Keeping configuration in the environment rather than in source means one build works everywhere, and secrets never need to appear in the repository.
How .env files work
A .env file holds simple KEY=value lines that a loader reads into the process environment at startup. It is a development convenience — in production you normally set real environment variables through your host or a secrets manager rather than shipping the file.
The mistakes that leak secrets
Never commit .env — add it to .gitignore on day one. Commit a .env.example with the keys and placeholder values instead, so new developers know what to set. And remember that anything exposed to a browser bundle is public: in front-end frameworks, variables with a public prefix are embedded in the client build and are not secret.
If a secret does get committed, rotate it. Removing the file does not help, because the value remains in the repository history.
Keeping it tidy
Use clear, uppercase names with underscores, group related keys, and validate required variables at startup so a missing value fails fast with a clear error instead of an obscure crash later.
