Skip to content

NestJS Configuration

Configuration keeps environment-specific values out of code. This lesson covers Nest configuration principles before the dedicated ConfigModule lesson.

Why Configuration Belongs Outside Code

Database URLs, JWT secrets, ports, and feature flags change between local, staging, and production. Nest applications should read these values from the environment (and optionally .env files) through a configuration layer, not literal strings in source files.

const port = process.env.PORT ?? 3000;
await app.listen(port);

Reading process.env directly works for tiny apps, but ConfigModule adds validation, namespacing, and DI-friendly access.

Configuration Goals

1. Externalize secrets and environment-specific values
2. Validate required config at startup (fail fast)
3. Provide typed access via ConfigService
4. Support namespaced config per feature domain
  • Fail at boot if required secrets are missing rather than failing on first request.
  • Never commit .env files that contain production secrets.
  • Use different env files or platform secrets per environment.
  • Prefer injection of ConfigService over scattering process.env reads.

Config Principles Cheatsheet

Practical rules for Nest configuration.

Rule Example
Externalize DB URL, JWT secret, SMTP credentials
Validate early Joi / Zod / class-validator schema at boot
Type access config.get<number>('port')
Namespace database.host, jwt.secret
Defaults carefully Default port OK; default JWT secret not OK

Twelve-Factor Style Config

Store config in the environment. Treat backing services as attached resources. Keep stage/prod parity so fewer 'works on my machine' surprises.

Feature Flags as Config

Boolean flags (ENABLE_BILLING_V2) let you ship dark features safely. Read them through ConfigService and gate routes or providers accordingly.

Common Mistakes

  • Hard-coding secrets in app.module.ts.
  • Providing insecure defaults for secrets "just so boot works".
  • Reading different env var names in different files without documentation.
  • Shipping the same .env to every environment.

Key Takeaways

  • Configuration isolates environment differences and secrets from code.
  • Validate required config at startup.
  • Prefer ConfigService over ad-hoc process.env usage.
  • Never commit production secrets.

Pro Tip

Document every env var in a .env.example with empty/placeholder values so onboarding does not require reverse-engineering ConfigModule factories.