Does ConfigModule Load .env in Production?
No, the ConfigModule does not automatically skip the .env file based on the NODE_ENV value. By default, ConfigModule.forRoot() will attempt to load the .env file regardless of whether your environment is set to development or production.
Understanding the Default Behavior
The @nestjs/config package relies on the dotenv library. The logic for loading files is governed by the ignoreEnvFile and envFilePath options, not by the NODE_ENV environment variable. If ignoreEnvFile is false (the default) and a .env file exists at the specified path, NestJS will load it into process.env.
Recommended Production Configuration
In production containers (such as Docker), it is a security best practice to avoid bundling .env files and instead rely on platform-supplied environment variables. To ensure your application behaves correctly in this scenario, use the following strategies:
- Disable File Loading: Set
ignoreEnvFile: true in production to ensure the app only uses the host's environment variables.
- Implement Schema Validation: Use a validation schema (via
joi or a custom function) to ensure required variables are present at bootstrap. This prevents the application from starting in a broken state if a critical variable is missing.
ConfigModule.forRoot({
isGlobal: true,
ignoreEnvFile: process.env.NODE_ENV === 'production',
validationSchema: Joi.object({
PORT: Joi.number().default(3000),
DATABASE_URL: Joi.string().required(),
}),
})
Overriding the Default Path
You can override envFilePath to point to a specific production file without using ignoreEnvFile. If you provide an array of paths, NestJS will load them in order, with later files overriding values from earlier ones. Note that if a specified file is missing, the module typically ignores it silently unless configured otherwise via underlying dotenv options.
Verification
To verify your current configuration, you can run a simple check in your main entry point:
// Temporary check for verification
console.log('NODE_ENV:', process.env.NODE_ENV);
console.log('Config Loaded:', process.env.MY_TEST_VARIABLE);
Diagnostic Detail: Are you using a custom configuration loader function (via the load property) in addition to the .env file? This may change how values are merged and prioritized.