Configuration & Environment Validation
Configuration & Environment Validation
Real applications behave differently across environments — local, staging, production — and they hold secrets like database passwords and API keys. Hard-coding these is a mistake. The official @nestjs/config package loads configuration from environment variables and .env files, and lets you validate it at startup.
Setting up ConfigModule
Install the package and import ConfigModule in your root module. isGlobal: true makes the config service injectable everywhere without re-importing:
By default it reads a .env file at the project root:
Reading configuration
Inject ConfigService and call get():
.gitignore and commit a .env.example with the keys but no real values. Secrets in source control are a serious security risk.
Custom configuration with namespaces
Grouping related settings into typed, namespaced config objects keeps things tidy:
Validating configuration at startup
The most valuable feature: fail fast. If a required variable is missing or malformed, the app should refuse to start rather than crash later. Pass a validation schema (commonly Joi):
JWT_SECRET stops deployment immediately with a clear message — instead of surfacing as a confusing runtime error on the first login attempt in production.
Summary
Use @nestjs/config to load environment variables and .env files, inject ConfigService to read them, and group settings with registerAs namespaces. Crucially, supply a validationSchema so the app fails fast at startup when configuration is missing or invalid. Keep secrets out of source control. Next: lifecycle hooks and the application context.