Environment variables are the standard way to configure Nest apps across machines. This lesson covers naming conventions, .env workflows, and production caveats.
Working With .env Locally
Locally, ConfigModule loads .env so you can set DATABASE_URL and JWT_SECRET without exporting shell variables every time. In production, platforms (Docker, Kubernetes, PaaS) inject env vars directly and you often disable env file loading.
Prefix feature-specific vars when helpful (STRIPE_SECRET_KEY).
Treat empty strings carefully: they are not the same as undefined.
Booleans arrive as strings; compare to 'true' or coerce explicitly.
Env Var Cheatsheet
Common Nest application variables.
Variable
Typical Use
NODE_ENV
development / production / test behavior
PORT
HTTP listen port
DATABASE_URL
ORM connection string
JWT_SECRET
Token signing key
CORS_ORIGIN
Allowed browser origins
LOG_LEVEL
Logging verbosity
File Precedence
When multiple env files are listed, earlier files can take precedence depending on ConfigModule settings. Keep a clear order like .env.local then .env and document it.
Containers and Secrets Managers
In Docker/Kubernetes, prefer secrets/config maps over baking .env into images. Rotate secrets without rebuilding images whenever possible.
Common Mistakes
Checking .env into git with real secrets.
Using different variable names in docs vs code.
Assuming boolean env vars are real booleans instead of strings.
Relying on .env files inside production containers.
Key Takeaways
Env vars configure Nest across environments.
Use .env locally and real platform secrets in production.
Document variables with .env.example.
Coerce and validate stringly-typed env values intentionally.
Pro Tip
Add a CI check that boots the Nest app with a minimal env set derived from .env.example so missing required keys fail the pipeline before deploy.
You now understand environment variables in Nest. Next, learn Custom Providers for advanced DI wiring.