Skip to content

NestJS Environment Variables

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.

# .env.example
NODE_ENV=development
PORT=3000
DATABASE_URL=postgres://user:pass@localhost:5432/nest
JWT_SECRET=replace-me-with-a-long-random-string

Commit .env.example, not .env. Each developer copies the example and fills private values.

Naming Conventions

NODE_ENV=production
PORT=3000
DATABASE_URL=...
JWT_SECRET=...
JWT_EXPIRES_IN=15m
CORS_ORIGIN=https://app.example.com
  • Use SCREAMING_SNAKE_CASE for env var names.
  • 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.